I am trying to send messages to Azure Event Hubs using the following piece of code:
var producer = new EventHubProducerClient(
ConfigurationManager.AppSettings["EventHubConnectionString"],
ConfigurationManager.AppSettings["EventHubName"]
);
The SAS key (connection string) is correct, it is at the instance level, (not namespace) as required by the Azure.Messaging.EventHubs.Producer library ( but i tried both ), unluckily it is returning following error:
---> 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)...
Thanks to @Jesse Squire for suggesting the root cause of the error.
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.
Please check the below steps if helps to fix the issue:
As given in this Microsoft Doc of EventHubProducerClient
Class,
there are multiple ways used to createEventHubProducerClient
that includes the method you have tried like Event Hub Instance SAS Connection String, Event Hub Namespace SAS Connection String and the other is using the credentials object with full namespace URL.
Above URL contains code examples of Configuring to send events to Event Hub.
One of the best practice/recommendations I came across reading the Azure Event Hubs authentication using SAS is:
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.
Refer to this MS Doc that contains the Configuration Steps from SAS Policy Generating to the Code Configuration from scratch.