AuthenticationError
azure.identity.AuthenticationError
Stack trace
azure.identity._exceptions.AuthenticationError: Failed to authenticate with managed identity. No token could be acquired from the managed identity endpoint.
File "/usr/local/lib/python3.9/site-packages/azure/identity/_internal/msal_credentials.py", line 123, in get_token
raise AuthenticationError(message)
azure.identity._exceptions.AuthenticationError: Failed to authenticate with managed identity. No token could be acquired from the managed identity endpoint. Why it happens
This error occurs when the Azure OpenAI client attempts to authenticate using a managed identity but cannot retrieve a valid access token. Common causes include the managed identity not being enabled on the Azure resource, incorrect environment configuration, or network issues preventing token endpoint access.
Detection
Monitor authentication exceptions from azure.identity.AuthenticationError and log detailed error messages including token acquisition failures to detect this issue early.
Causes & fixes
Managed identity is not enabled on the Azure resource (VM, App Service, or Function).
Enable the system-assigned or user-assigned managed identity on your Azure resource in the Azure portal or via CLI.
Environment variables or Azure SDK configuration missing or incorrect for managed identity authentication.
Ensure no conflicting environment variables like AZURE_CLIENT_ID, AZURE_TENANT_ID, or AZURE_CLIENT_SECRET are set when using managed identity, and that the Azure SDK is configured to use DefaultAzureCredential.
Network restrictions or firewall rules block access to the managed identity endpoint (169.254.169.254).
Allow outbound traffic to the managed identity endpoint IP address and port 80 from your Azure resource.
Code: broken vs fixed
from azure.ai.openai import OpenAIClient
from azure.identity import ManagedIdentityCredential
client = OpenAIClient(endpoint="https://my-resource.openai.azure.com/", credential=ManagedIdentityCredential())
response = client.chat.completions.create(model="gpt-4o", messages=[{"role": "user", "content": "Hello"}]) # Raises AuthenticationError import os
from azure.ai.openai import OpenAIClient
from azure.identity import DefaultAzureCredential
# Use DefaultAzureCredential which supports managed identity and local dev auth
credential = DefaultAzureCredential()
client = OpenAIClient(endpoint=os.environ["AZURE_OPENAI_ENDPOINT"], credential=credential)
response = client.chat.completions.create(model="gpt-4o", messages=[{"role": "user", "content": "Hello"}])
print(response.choices[0].message.content) # Fixed authentication using managed identity Workaround
Catch AuthenticationError and fallback to using a service principal credential with client ID and secret if managed identity is unavailable.
Prevention
Always enable managed identity on your Azure resource and use DefaultAzureCredential to handle token acquisition automatically, avoiding manual token management.