我尝试使用以下代码将消息发送到 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/