Ariel Kliger
Ariel Kliger

Reputation: 11

Azure user assigned managed Identity authentication fails

I have an app service in Azure, and I want to use it to send events to the Azure Event Hub.

I'm using a user-assigned managed identity that I connected to my app service.

I'm using:

new DefaultAzureCredential()

to authenticate, but Im getting this error:

ManagedIdentityCredential Authentication Failed

Service request failed.

Status: 400 (Bad Request)

Content:

{ "statusCode": 400, "message": "Unable to load the proper Managed Identity.", "correlationId": "183e1509-0635-4dc3-8463-d1891f7307c7" }

Headers:

Date: Sun, 14 Jul 2024 14:46:19 GMT
Server: Kestrel
Transfer-Encoding: chunked
X-CORRELATION-ID: REDACTED
Content-Type: application/json; charset=utf-8

I can't really figure out what the issue is.

I tried restarting the web app, deleting the managed identity, and creating a new one, but the error persists.

Upvotes: 1

Views: 1428

Answers (1)

Venkatesan
Venkatesan

Reputation: 10455

ManagedIdentityCredential Authentication Failed Service request failed. Status: 400 (Bad Request) { "statusCode": 400, "message": "Unable to load the proper Managed Identity.", "correlationId": "183e1509-0635-4dc3-8463-d1891f7307c7" }

I agree with Juunas's comment, To authenticate with a user-managed identity, you need to specify the Client ID of your user-managed identity, and the system needs to know which one you want to use.

You can get the client id from your Azure portal.

Portal: enter image description here

You can use client id like below in your code:

Code:

string userAssignedClientId = "<your managed identity client ID>";
var credential = new DefaultAzureCredential( new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });

Full code to send an event the event hub with managed identity.

using Azure.Identity;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;
using System.Text;

int numOfEvents = 3;

string userAssignedClientId = "<your managed identity client ID>";
var credential = new DefaultAzureCredential( new DefaultAzureCredentialOptions { ManagedIdentityClientId = userAssignedClientId });

EventHubProducerClient producerClient = new EventHubProducerClient(
    "<EVENT_HUB_NAMESPACE>.servicebus.windows.net",
    "<HUB_NAME>",
    credential;

using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

for (int i = 1; i <= numOfEvents; i++)
{
    if (!eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes($"Event {i}"))))
    {
        throw new Exception($"Event {i} is too large for the batch and cannot be sent.");
    }
}

try
{
    await producerClient.SendAsync(eventBatch);
    Console.WriteLine($"A batch of {numOfEvents} events has been published.");
    Console.ReadLine();
}
finally
{
    await producerClient.DisposeAsync();
}

Reference: DefaultAzureCredential Class (Azure.Identity) - Azure for .NET Developers | Microsoft Learn

Upvotes: 1

Related Questions