c# - 如何使用 SAS 解决 Azure 事件中心中的授权错误 (401)?

标签 c# azure events azure-eventhub

我尝试使用以下代码将消息发送到 Azure 事件中心:

    var producer = new EventHubProducerClient(
            ConfigurationManager.AppSettings["EventHubConnectionString"],
            ConfigurationManager.AppSettings["EventHubName"]
        );

SAS key (连接字符串)是正确的,它位于实例级别(而不是命名空间),如Azure.Messaging.EventHubs.Producer库所要求的(但我尝试了两者), 不幸的是它返回以下错误:

---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.

   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebRequest.<>c.<GetResponseAsync>b__68_2(IAsyncResult iar)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)...

最佳答案

感谢 @Jesse Squire 提出错误的根本原因

That does not appear to be an Event Hubs error. There is no HTTP stack in Event Hubs, the client is entirely AMQP-based. It's also worth noting that the client will lazily establish the connection; if you're seeing it for that snippet, it would imply that something is happening within the configuration system.

请检查以下步骤是否有助于解决问题:

如本中所示Microsoft Doc EventHubProducerClient类, 有多种方法可用于创建EventHubProducerClient,其中包括您尝试过的方法,例如事件中心实例 SAS 连接字符串、事件中心命名空间 SAS 连接字符串,另一种是使用具有完整命名空间 URL 的凭据对象。 以上 URL 包含配置将事件发送到事件中心的代码示例。

我在阅读使用 SAS 的 Azure 事件中心身份验证时遇到的最佳实践/建议之一是:

Microsoft recommends that you use Azure AD credentials when possible as a security best practice, rather than using the shared access signatures, which can be more easily compromised. While you can continue to use shared access signatures (SAS) to grant fine-grained access to your Event Hubs resources, Azure AD offers similar capabilities without the need to manage SAS tokens or worry about revoking a compromised SAS.

引用这个MS Doc其中包含从头开始生成 SAS 策略到代码配置的配置步骤。

关于c# - 如何使用 SAS 解决 Azure 事件中心中的授权错误 (401)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73237707/

相关文章:

c# - 如何将 DatePicker 添加到我的 MVC3 C# 站点

c# - 在每次调用时调用一个方法

C# 原始静默溢出 - 通过 C# 的 CLR

azure - Calico GlobalNetworkPolicy 排除不起作用

c++ - Mac事件点击只是延迟丢弃的事件

c# - Console 程序中的任务和异步

security - 如果我不控制身份验证服务,如何使用不记名 token 保护 API 服务

azure - 如何在 Terraform 的 virtual_machine 资源中使用共享镜像计划数据,例如发布者、报价和 sku

flash - Flash 中的 onMouseUp/Down 和 onPress/Release 事件有什么区别?

events - 在 Silverlight 4 Datagrid 上实现双击事件