Cloud & Infrastructure Bug Report

Azure managed identity gets 401 from our API: token issued for the wrong audience

A Function App calling our internal API with its managed identity got 401 invalid_token on every request. The token was valid, but its aud claim was Azure Resource Manager. Then the second identity on the app picked the wrong client. How we decoded it and fixed both.

Marcus Lindqvist Marcus Lindqvist @marcuslindqvist · November 26, 2026 · 8 min read · 112 Views
629-azure-managed-identity-401-wrong-token-audience

We moved the nightly billing sync from a client secret to the Function App's managed identity. The sync calls our internal Orders API, an ASP.NET Core app protected by Microsoft Entra ID. After the deploy, every call returned 401. The Function log only showed the status code; the API response header had the useful part:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'https://management.azure.com/' is invalid"

On the API side, with IdentityModelEventSource.ShowPII turned on in a test slot, the log said:

IDX10214: Audience validation failed. Audiences: 'https://management.azure.com/'.
Did not match: validationParameters.ValidAudience: 'api://orders-api' or
validationParameters.ValidAudiences: 'null'.

Reproducing it

The new code, copied from a sample that listed resource groups:

var credential = new DefaultAzureCredential();
var token = await credential.GetTokenAsync(
    new TokenRequestContext(new[] { "https://management.azure.com/.default" }));

http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", token.Token);
var res = await http.GetAsync("https://orders-api.example.com/v1/invoices?since=2027-01-29");

Every run returned 401, from the Function App and from a developer laptop signed in with az login.

What we ruled out

  • Expired token. The exp claim was an hour ahead. An expired token gives a different description ("The token expired at ...").

  • Wrong tenant. The iss and tid claims matched our tenant.

  • Clock skew. Both apps run on Azure with synced clocks, and nbf was in the past.

  • API configuration change. The API had not been deployed in two weeks, and the old secret-based client still worked.

Root cause

A token is issued for one resource, and its aud claim names that resource. The sample asked for a token for Azure Resource Manager (https://management.azure.com/.default), so Entra ID issued exactly that: a valid token that only Azure Resource Manager should accept. Our API correctly rejected it because it expects aud to be its own App ID URI, api://orders-api.

When we fixed the scope, a second problem appeared: the Function App has two identities (system assigned, and a user-assigned one called id-billing-sync that held the API permission). DefaultAzureCredential used the system-assigned identity, which had no app role on the API, so the API returned 403. Both were configuration mistakes in the caller.

What is happening under the hood

With Entra ID, the client asks for a token for a specific resource. In MSAL and Azure Identity libraries, that is expressed as a scope of the form <resource>/.default. For a managed identity, the token comes from the platform's identity endpoint (IMDS on VMs, the IDENTITY_ENDPOINT on App Service and Functions), and the resource parameter becomes the token's aud.

The API, through the JWT bearer handler, validates:

  • the signature against the tenant's signing keys,

  • iss against the tenant,

  • aud against its configured audiences,

  • exp and nbf,

  • and, in our authorization policy, the roles claim.

A token for one API is never valid for another. That is the point of the audience: a token leaked from one service cannot be replayed against a different one.

Two more details matter for our case:

  • v1 versus v2 audience format. If the API's app registration accepts v1 tokens (the default when accessTokenAcceptedVersion is null or 1), aud is the App ID URI. With v2 tokens, aud is the application (client) ID GUID. Managed identity tokens follow the API's accepted version. Configure both values as valid audiences to avoid surprises.

  • App roles for managed identities. A managed identity cannot be given delegated permissions; it gets application permissions through an app role assignment on the API's service principal. The portal has no button for this, so it is done through Microsoft Graph, Azure CLI or PowerShell. The assigned role appears in the roles claim.

Environment

Component

Version / value

Caller

Azure Functions, .NET 8 isolated worker, Flex Consumption

Identities on caller

System assigned + user assigned id-billing-sync

Library

Azure.Identity 1.13

API

ASP.NET Core 8, Microsoft.Identity.Web 3.x, App Service

API registration

App ID URI api://orders-api, app role Invoices.Read, v1 tokens

Minimal reproduction

Get a token from the CLI for the wrong resource and decode it:

az account get-access-token --resource https://management.azure.com/ --query accessToken -o tsv \
  | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{aud, iss, appid, roles}'
{
  "aud": "https://management.azure.com/",
  "iss": "https://sts.windows.net/00000000-0000-0000-0000-000000000000/",
  "appid": "04b07795-8ddb-461a-bbee-02f9e1bf7b46",
  "roles": null
}

Calling the API with this token returns the 401 above. (The base64 step may need padding; jwt.ms, Microsoft's decoder, does the same in a browser and keeps the token client-side.)

Who is affected

Any caller of a custom Entra-protected API that:

  • copies a token sample written for Azure Resource Manager, Graph, Storage or Key Vault,

  • uses the legacy resource parameter with a trailing-slash mismatch, or

  • has more than one managed identity and lets the library pick one.

The fix

Request a token for the API, and name the user-assigned identity explicitly:

-var credential = new DefaultAzureCredential();
-var token = await credential.GetTokenAsync(
-    new TokenRequestContext(new[] { "https://management.azure.com/.default" }));
+var credential = new ManagedIdentityCredential(
+    ManagedIdentityId.FromUserAssignedClientId(config["BILLING_SYNC_CLIENT_ID"]));
+var token = await credential.GetTokenAsync(
+    new TokenRequestContext(new[] { "api://orders-api/.default" }));

We moved the token logic into a DelegatingHandler so it runs per request and benefits from the library's token cache, instead of setting a static header that expires after an hour.

Then assign the app role to the user-assigned identity's service principal (one-time, done by an admin of the API's app registration):

API_SP_ID=$(az ad sp show --id api://orders-api --query id -o tsv)
MI_SP_ID=$(az identity show -g rg-billing -n id-billing-sync --query principalId -o tsv)
ROLE_ID=$(az ad sp show --id api://orders-api \
  --query "appRoles[?value=='Invoices.Read'].id | [0]" -o tsv)

az rest --method POST \
  --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$MI_SP_ID/appRoleAssignments" \
  --body "{\"principalId\":\"$MI_SP_ID\",\"resourceId\":\"$API_SP_ID\",\"appRoleId\":\"$ROLE_ID\"}"

On the API, accept both audience forms so a later switch to v2 tokens does not break callers:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        options.TokenValidationParameters.ValidAudiences = new[]
        {
            "api://orders-api",
            "11111111-2222-3333-4444-555555555555"
        };
    }, options => builder.Configuration.Bind("AzureAd", options));

Alternatives and trade-offs

  • DefaultAzureCredential with AZURE_CLIENT_ID set to the user-assigned identity works too, and keeps local development on az login. We chose the explicit ManagedIdentityCredential in production so a misconfigured environment fails loudly instead of falling back to another credential type.

  • Using only the system-assigned identity. Simpler, but it is deleted with the app, so role assignments must be recreated if the Function App is rebuilt.

  • Easy Auth (App Service authentication) on the API does the same audience check before the request reaches code. It must list the same allowed audiences.

How to test the fix

From the Function App's Kudu console (or a test Function), fetch a token and inspect the claims:

curl -s -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" \
  "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=api://orders-api&client_id=$BILLING_SYNC_CLIENT_ID" \
  | jq -r .access_token | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{aud, oid, roles}'

Expected: aud is api://orders-api, oid matches the user-assigned identity's principal ID, and roles contains Invoices.Read. Then run the sync once manually and check for HTTP 200.

Confirming in production

In Application Insights for the API, we filtered requests from the sync's operation name and compared status codes before and after:

requests
| where timestamp > ago(2d) and name startswith "GET /v1/invoices"
| summarize count() by resultCode, bin(timestamp, 1h)

401 and 403 dropped to zero after the deploy; the nightly run completed with 200s only. Entra ID sign-in logs, under "Managed identity sign-ins", showed id-billing-sync with resource orders-api.

Regression guard

  • An integration test in the caller's pipeline requests a token with the configured scope and asserts aud and roles before deploying.

  • The app role assignment is in Terraform (azuread_app_role_assignment), so a rebuilt identity gets its role back automatically.

  • Code review checklist item: any .default scope string must match the API being called.

Security implications

The audience check did its job: a token for Azure Resource Manager was refused by our API. The dangerous "fix" would have been to disable audience validation or to accept any audience in the tenant, which lets any token leaked from any service be replayed against the API. We also removed the old client secret from Key Vault and the app registration after the switch, so the credential that could leak no longer exists. Note that managed identity tokens are cached for up to 24 hours, so removing a role assignment does not take effect instantly.

Prevention checklist

  • Decode the token and read aud, roles and oid before debugging anything else.

  • Use <App ID URI>/.default for custom APIs; never reuse scopes from other samples.

  • With several managed identities, always pass the client ID.

  • Manage app role assignments for managed identities as code.

  • Keep audience validation strict and list both App ID URI and client ID.

References

Add a label

#jwt #azure #managed-identity #entra-id #aspnet-core
Written by
Marcus Lindqvist @marcuslindqvist

I have spent most of the last decade on mobile teams, first native iOS, then React Native and Flutter for companies that needed one team to ship to both stores. The work I enjoy most is the unglamorous part between "it runs on my phone" and "it is live for a million users": code signing, release builds, store review, crash triage and background behaviour that differs on every Android vendor. Most of the bugs I write about here cost a release day. Each post shows the exact error, what we ruled out, the fix and how we proved it in the next build, so you can get your own release out the door sooner.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.