Join our Newsletter — 33% off our NHI Course
Home› Guides› How to fix Azure managed identity token errors:…
Guide Cloud & Workload Identity

How to fix Azure managed identity token errors: IMDS, ManagedIdentityCredential and audience issues

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 13 min read
On this page

Azure managed identity token errors almost always come from one of four places: the token endpoint cannot be reached, the wrong identity is requested, the wrong audience is requested, or DefaultAzureCredential picked a different credential than you expected. This guide walks through each one using the messages the Azure Identity libraries and the token endpoints actually return, and shows how to fix them without falling back to a client secret.

It is written for developers, platform engineers and identity teams running code on Azure virtual machines, App Service, Azure Functions and Azure Kubernetes Service (AKS). For how managed identities work and how to secure them, see our Azure Managed Identities Security Guide. If the token works but the call is then refused, see our Azure AuthorizationFailed Troubleshooting Guide.

This is an independent guide from NHI Mgmt Group, based on Microsoft's public documentation as of November 2026. It is not sponsored or reviewed by Microsoft. Product features change, so confirm settings against Microsoft's current documentation.

Key takeaways

  • Work out first whether you have a token problem or a permission problem. A token problem fails before any call reaches the target service; a permission problem returns 401 or 403 from the service.
  • On virtual machines the token comes from the Instance Metadata Service (IMDS) at 169.254.169.254. IMDS needs the Metadata: true header and does not support proxies.
  • On App Service and Azure Functions the token comes from a local token service named in IDENTITY_ENDPOINT, protected by IDENTITY_HEADER.
  • With user assigned identities, always pass the identity's client ID. Otherwise the endpoint tries the system assigned identity, which may not exist.
  • The resource you request becomes the token's audience. Request the right resource for the service you are calling.
  • Microsoft recommends replacing DefaultAzureCredential with a specific credential such as ManagedIdentityCredential in production, or limiting the chain with AZURE_TOKEN_CREDENTIALS.
  • Role and group changes can take hours to show up in managed identity tokens because of a back end cache of around 24 hours. Waiting is sometimes the fix.

How a managed identity token is issued

Code never holds a secret for a managed identity. Instead it asks a local endpoint on the host for an access token, and the platform obtains that token from Microsoft Entra ID on its behalf. Microsoft documents two main endpoints:

HostEndpointRequired headerAPI version
Azure virtual machines and scale setshttp://169.254.169.254/metadata/identity/oauth2/tokenMetadata: true2018-02-01 or later
App Service and Azure FunctionsValue of IDENTITY_ENDPOINTX-IDENTITY-HEADER set to the value of IDENTITY_HEADER2019-08-01

Both take a resource parameter, and both accept an optional identifier for a user assigned identity: client_id, object_id or msi_res_id on IMDS, and client_id, principal_id or mi_res_id on App Service. Microsoft explains that the header requirements exist to help mitigate server side request forgery, and that the App Service platform rotates the IDENTITY_HEADER value.

The Azure Identity libraries wrap these endpoints. ManagedIdentityCredential detects the host and calls the right one; DefaultAzureCredential tries a chain of credentials, of which managed identity is one. Most confusing errors come from not knowing which layer failed, so the first step is always to turn on library logging.

Step one: turn on logging and read the real error

The Azure Identity troubleshooting guide for Python describes the most common top level message: "DefaultAzureCredential failed to retrieve a token from the included credentials." Its cause is that every credential in the chain raised CredentialUnavailableError, and the documented fix is to enable logging to see which credentials were tried, then follow the troubleshooting section for each one. The same pattern applies to the .NET, Java and JavaScript libraries.

With logging on, look for the line that shows what the managed identity credential did. Microsoft's credential chain documentation gives an example: during local development the log shows ManagedIdentityCredential will use IMDS followed by no response from the IMDS endpoint, and the chain moves on. On a developer laptop that is normal. In a deployed workload it means the host is not providing a managed identity endpoint at all.

A second documented case catches many teams out. The troubleshooting guide notes that a ClientAuthenticationError with a 401 or 403 from the service can mean authentication succeeded but with the wrong account. The fix is to find which credential returned the token and exclude it. On a build agent or a shared VM, a signed in Azure CLI session or leftover environment variables can win the chain ahead of the managed identity.

Endpoint unreachable: IMDS and the local token service

The Python troubleshooting guide documents these managed identity messages on virtual machines:

MessageDocumented causeFix
No response received from the managed identity endpointNo response from IMDS, or the request timed outConfirm a managed identity is configured on the VM and that IMDS is reachable
The request failed due to a gateway errorIMDS returned 502 or 504Calls via proxy or gateway are not supported; bypass proxies for 169.254.169.254
The requested identity hasn't been assigned to this resourceIMDS returned 400For user assigned, check the client_id; for system assigned, confirm it is enabled

Things to check when IMDS does not answer:

  • Proxy settings. If HTTP_PROXY or HTTPS_PROXY is set on the VM or in a container image, add 169.254.169.254 to NO_PROXY. Microsoft states that IMDS is not intended to be used behind a proxy.
  • Host firewall and routing. Local firewall rules, custom routes inside containers and some network appliances block link local traffic.
  • Containers on a VM. Containers on a bridge network may not reach the host's link local address; test from inside the container, not just the host.
  • The identity itself. Check in the portal or with the Azure CLI that the VM has a system assigned identity enabled or the user assigned identity attached.

On App Service and Functions, the documented message is "ManagedIdentityCredential authentication unavailable", caused when "the environment variables configured by the App Services host weren't present". The fix is to make sure the managed identity is configured on the app and that IDENTITY_ENDPOINT and IDENTITY_HEADER are set. If you run the same code in a custom container or a local emulator, those variables will be missing.

IMDS status codes and retries

When you call IMDS directly, or when a library surfaces its status code, Microsoft's token documentation explains what each response means:

StatusMeaning from MicrosoftAction
400 bad_request_102Required metadata header not specifiedSend Metadata: true; do not retry
400 invalid_resourceThe application for the resource URI was not found in the tenant (AADSTS50001)Fix the resource URI; do not retry
401 (several errors, including invalid_scope)Malformed request or VM not configured for managed identitiesCheck the request and VM configuration; do not retry
404 or timeoutIMDS is updatingRetry with exponential back off
410IMDS is updatingWait; IMDS is available within 70 seconds
429Throttle limit reachedRetry with exponential back off
500 unknownFailed to retrieve the token from Entra IDCheck the identity is enabled and the resource is correct

Microsoft recommends a retry policy of five retries with back off up to 60 seconds, and warns that retrying 5xx errors too fast can cause 429 throttling. It also says not to branch code on error_description, because its text can change. The Azure Identity libraries already apply retries, so custom retry loops around them usually make throttling worse.

Microsoft also states that the managed identities subsystem caches tokens but that you should still cache tokens in your own code. Requesting a fresh token for every call is a common cause of 429 responses under load. Managed identity responses carry an empty refresh_token; when expires_on passes, request a new token.

Wrong identity: user assigned client IDs

The App Service documentation carries a clear warning: if you want a token for a user assigned identity, include one of the optional identifier properties; "Otherwise, the token service tries to get a token for a system-assigned identity, which might or might not exist." The IMDS documentation likewise says the identifier is required when the VM has more than one user assigned identity.

In code, set the identity explicitly. In the Azure Identity libraries, pass the client ID when constructing ManagedIdentityCredential, or set AZURE_CLIENT_ID for DefaultAzureCredential. Common mistakes:

  • Using the identity's object (principal) ID where a client ID is expected.
  • Copying the client ID of a different identity from another environment.
  • Attaching a new user assigned identity and detaching the old one without updating configuration.
  • Setting AZURE_CLIENT_ID for a managed identity while also setting AZURE_TENANT_ID and AZURE_CLIENT_SECRET, so the environment credential uses a service principal secret instead.

Wrong audience: resources and scopes

The IMDS documentation explains that the resource parameter is the App ID URI of the target, such as https://management.azure.com/ or https://vault.azure.net, and that it becomes the token's aud claim. A token is only useful for the service it was issued for. A token for Azure Resource Manager sent to Key Vault, Azure Storage or your own API will be rejected by that service, usually with 401.

The Azure Identity libraries take scopes rather than resources. For a managed identity, the scope is the resource followed by /.default, for example https://vault.azure.net/.default. Check for these audience problems:

  • A client library configured with the wrong scope, often copied from another service.
  • A custom API whose App ID URI differs from the value the caller requests, so the call fails with invalid_resource or the API rejects the audience.
  • Sovereign clouds, where resource URIs differ from the public cloud values.
  • Trailing slash differences in the resource string, which some APIs check strictly.

Decode a token during debugging, without logging it in full, and compare the aud claim with what the target service expects. Also confirm the token's tenant is the one the resource lives in; the troubleshooting guide documents the message "The current credential is not configured to acquire tokens for tenant" and the additionally_allowed_tenants setting for multi tenant cases.

DefaultAzureCredential in production

Microsoft's credential chain guidance for Python lists the order DefaultAzureCredential tries: environment, workload identity, managed identity, shared token cache (Windows only), Visual Studio Code, Azure CLI, Azure PowerShell, Azure Developer CLI, then interactive browser (off by default) and broker. It advises that once you deploy to Azure, you should "replace DefaultAzureCredential with a specific TokenCredential implementation, such as ManagedIdentityCredential", citing debugging difficulty, the overhead of trying each credential in turn, and unpredictable behaviour when host environment variables change which credential is used.

If you keep DefaultAzureCredential, restrict it. The same page documents AZURE_TOKEN_CREDENTIALS: the value prod excludes developer tool credentials, and a single credential name such as ManagedIdentityCredential limits the chain to that one. Setting require_envvar=True makes construction fail if the variable is missing, so a misconfigured host fails loudly instead of picking up a stray CLI login. Check your language's documentation for the equivalent setting.

On AKS, use WorkloadIdentityCredential or managed identity as your platform intends. The troubleshooting guide documents AADSTS700211 ("No matching federated identity record found for presented assertion issuer") when identity bindings are used without the proxy setting, and notes that identity binding mode is not supported through DefaultAzureCredential. For federated credential review, see our How to audit Entra workload identity federated credentials guide.

Token works, permissions do not: the 24 hour cache

Microsoft's managed identity best practice guidance explains that tokens carry group and role membership as claims, and that "the back-end services for managed identities maintain a cache per resource URI for around 24 hours". As a result, "it can take several hours for changes to a managed identity's group or role membership to take effect", and it is not currently possible to force a managed identity's token to refresh before expiry.

If you have just added the identity to a group and the call still fails, the token may simply be stale. Microsoft recommends assigning permissions directly to a user assigned managed identity rather than adding and removing managed identities from Entra groups that hold permissions. That avoids the delay and keeps the permission path clear. Our How to find over-privileged Azure managed identities guide covers reviewing those direct assignments.

Why a client secret is the wrong fix

When managed identity is fiddly, the tempting workaround is to create an app registration, generate a client secret and set AZURE_CLIENT_SECRET. The environment credential is first in the default chain, so the error vanishes. The workload now depends on a secret that can leak through configuration, logs and images, must be rotated and is usable from anywhere.

NHI Mgmt Group recommends treating any secret added during troubleshooting as a defect with an owner and a removal date. Track which workloads hold AZURE_CLIENT_SECRET and confirm each one has a reason it cannot use managed identity. If a secret is truly needed, store it in a vault; see our Azure Key Vault Security Guide.

Common failure patterns

  • Proxy in the path: a corporate proxy variable routes IMDS traffic and returns gateway errors.
  • Missing client ID: a user assigned identity is attached but not specified, so the endpoint looks for a system assigned identity.
  • Wrong audience: a token for one service is sent to another and rejected with 401.
  • Chain surprise: DefaultAzureCredential picks up environment variables or a CLI login on a build agent ahead of the managed identity.
  • Token per request: no caching, leading to IMDS throttling under load.
  • Expecting instant role changes: a group change made minutes ago is not yet in the token.
  • Secret fallback: a client secret added to "fix" the error and never removed.

Practitioner checklist

  • Enable Azure Identity logging and find which credential failed or succeeded.
  • Confirm the identity is enabled or attached on the host, and that IDENTITY_ENDPOINT and IDENTITY_HEADER are present on App Service and Functions.
  • Exclude 169.254.169.254 from proxies and test IMDS from inside containers.
  • Pass the client ID for every user assigned identity.
  • Check the requested resource or scope against the target service and decode the aud claim.
  • Use ManagedIdentityCredential in production, or set AZURE_TOKEN_CREDENTIALS with require_envvar=True.
  • Cache tokens and rely on library retries rather than custom loops.
  • Allow for the 24 hour cache after group or role changes, and prefer direct assignments.
  • Remove any client secret added while troubleshooting.

Standards and references

Related NHI Mgmt Group resources: Azure Managed Identities Security Guide · How to find over-privileged Azure managed identities · Azure AuthorizationFailed Troubleshooting Guide · Azure Key Vault Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.