The app worked with an API key. You switched it to Entra ID or a managed identity, and now every call fails with one of these:
401 Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired.
401 {"code": "PermissionDenied", "message": "Principal does not have access to API/Operation."}
The first is a token problem. The second means the token is fine but the identity has no data-plane role. This post shows how to tell which one you have and fix it in a few minutes.
Symptom → cause → fix
| Symptom | Likely cause | Fix |
|---|---|---|
audience is incorrect | Token requested for the wrong resource (often management.azure.com) | Request the https://cognitiveservices.azure.com/.default scope |
PermissionDenied / Principal does not have access | Identity has Owner or Contributor but no data-plane role | Assign Cognitive Services OpenAI User on the resource |
| Works on your laptop, fails in Azure | Code used your user account locally, the managed identity in Azure | Assign the role to the managed identity's principal |
| Fails only with a user-assigned identity | Client ID not passed, so no identity or the wrong one is used | Set AZURE_CLIENT_ID or pass client_id |
| 401 with a valid-looking token | Token from a different tenant | Check the tid claim, log in to the right tenant |
| 401 on a regional endpoint | The endpoint has no custom subdomain, so Entra tokens are rejected | Use https://<resource>.openai.azure.com |
| Worked for 10 minutes after the role was added, then nothing changed | Role propagation delay | Wait a few minutes, then retry with a new token |
403 Public access is disabled | Network rule, not identity | See your private endpoint and firewall settings |
Check 1: decode the token you are actually sending
Get a token the same way the app does and look at its claims. With the CLI, signed in as the identity that should work:
TOKEN=$(az account get-access-token \
--resource https://cognitiveservices.azure.com \
--query accessToken -o tsv)
python3 - "$TOKEN" <<'EOF'
import sys, json, base64
p = sys.argv[1].split(".")[1]
p += "=" * (-len(p) % 4)
c = json.loads(base64.urlsafe_b64decode(p))
print({k: c.get(k) for k in ("aud", "tid", "oid", "appid", "upn", "exp")})
EOF
Check three claims:
audshould behttps://cognitiveservices.azure.com. If it ishttps://management.azure.com, your code asked for an Azure Resource Manager token. That token works foraz cognitiveservicescommands but not for chat completions.tidshould be the tenant that owns the Azure OpenAI resource.oidis the object ID of the identity. You need it for the role check below.
Tip
Newer Microsoft Foundry samples use the
https://ai.azure.com/.defaultscope. If a sample with that scope fails against an older*.openai.azure.comendpoint, or the other way round, try the other audience before you go further. Check which one the current docs show for your endpoint type.
Then test the call outside your app so you know whether the problem is the identity or the code:
ENDPOINT=https://my-aoai.openai.azure.com
curl -s -o /dev/null -w "%{http_code}\n" \
"$ENDPOINT/openai/deployments/gpt-4o-prod/chat/completions?api-version=2024-10-21" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"ping"}],"max_tokens":5}'
Replace the deployment name and API version with your own. A 200 here and a 401 from the app means the app is using a different credential.
Check 2: endpoint, subdomain and local auth
RG=rg-genai-prod; NAME=my-aoai
az cognitiveservices account show -n $NAME -g $RG --query "{endpoint:properties.endpoint, subdomain:properties.customSubDomainName, disableLocalAuth:properties.disableLocalAuth, publicNetworkAccess:properties.publicNetworkAccess}" -o jsonc
- Entra ID authentication needs a custom subdomain. Call the
https://<subdomain>.openai.azure.comendpoint, not a regionalhttps://<region>.api.cognitive.microsoft.comone. disableLocalAuth: truemeans keys are turned off. That is the target state, but confirm every app has moved before you turn it on.- If
publicNetworkAccessisDisabledand you get a 403 about public access, the problem is the network. Fixing roles will not help.
Check 3: the data-plane role
The usual cause of PermissionDenied is that the identity has only control-plane roles. Owner and Contributor let you create deployments and read keys. They do not include the data actions (Microsoft.CognitiveServices/accounts/OpenAI/*) that inference calls need.
ID=$(az cognitiveservices account show -n $NAME -g $RG --query id -o tsv)
OID=<oid from the token>
az role assignment list --assignee $OID --scope $ID \
--include-inherited --query "[].{role:roleDefinitionName, scope:scope}" -o table
You need one of these on the resource, its resource group or the subscription:
| Role | Use it for |
|---|---|
Cognitive Services OpenAI User | Apps and users that only call models. Use this one for workloads |
Cognitive Services OpenAI Contributor | Also lets the identity fine-tune and manage some data-plane objects |
Cognitive Services User | Broader. Covers all Cognitive Services data actions. Avoid it for apps |
Assign the narrow role to the identity:
az role assignment create \
--assignee-object-id $OID \
--assignee-principal-type ServicePrincipal \
--role "Cognitive Services OpenAI User" \
--scope $ID
Use --assignee-principal-type User for a person, or Group for a group. Role assignments can take several minutes to apply. Wait, then get a new token and retry before you assume the fix failed.
Warning
Don't fix
PermissionDeniedby giving the app Owner or Contributor. Those roles don't fix data-plane access, and they let the app read keys and delete deployments.
Check 4: which credential did DefaultAzureCredential pick?
DefaultAzureCredential tries a chain of credentials and uses the first one that returns a token. That causes most "works for me, fails in prod" cases:
- On a laptop it may use environment variables for an old service principal before it reaches your
az loginsession. - In App Service, Functions, AKS or a VM with a user-assigned identity, it needs the client ID. Without it, the call fails or picks a different identity.
Find the right principal and client ID:
# System-assigned identity on a web app
az webapp identity show -n my-app -g $RG --query principalId -o tsv
# User-assigned identity
az identity show -n id-chat-api -g $RG --query "{clientId:clientId, principalId:principalId}" -o jsonc
Pin the credential in code and turn on identity logging while you debug:
import logging, os
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import AzureOpenAI
logging.basicConfig(level=logging.INFO)
logging.getLogger("azure.identity").setLevel(logging.DEBUG)
credential = DefaultAzureCredential(
managed_identity_client_id=os.environ.get("AZURE_CLIENT_ID"),
exclude_environment_credential=True, # skip stale service principal env vars
)
token_provider = get_bearer_token_provider(
credential, "https://cognitiveservices.azure.com/.default"
)
client = AzureOpenAI(
azure_endpoint="https://my-aoai.openai.azure.com",
azure_ad_token_provider=token_provider,
api_version="2024-10-21",
)
r = client.chat.completions.create(
model="gpt-4o-prod", # the deployment name, not the model name
messages=[{"role": "user", "content": "ping"}],
max_tokens=5,
)
print(r.choices[0].message.content)
The debug log names the credential that returned the token. Assign the role to that identity, or change the chain so the intended identity is used.
Pass azure_ad_token_provider, not a fixed azure_ad_token. A fixed token expires after about an hour, and long-running workers then start failing with the "have expired" form of the 401.
Check 5: API Management or another gateway in front
If APIM calls Azure OpenAI with its managed identity, the policy must request the right audience and APIM's identity needs the role:
<authentication-managed-identity resource="https://cognitiveservices.azure.com" />
Check the role with the APIM identity's principal ID:
az apim show -n my-apim -g $RG --query identity.principalId -o tsv
A 401 from the gateway itself, before the backend is called, is a gateway subscription or JWT policy problem, not an Azure OpenAI one. The gateway trace shows which hop rejected the call.
Prevent it next time
- Grant
Cognitive Services OpenAI Userto a group or to each workload identity in the same IaC change that creates the deployment. - Use one user-assigned identity per app and set
AZURE_CLIENT_IDin its configuration, so the credential chain can't pick the wrong one. - Add a startup check that requests a token, logs the
oidandaud, and makes a 5-token test call. A bad identity then fails the deployment, not the first user request. - Once every app uses Entra ID, set
disableLocalAuthtotrueso nobody goes back to keys. - Alert on 401 and 403 responses in the
AzureOpenAIRequestsmetric, split byStatusCode, so an identity change shows up before users report it.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get