{"record":{"id":"8d51c1ea55ba844e","repo":"mastra-ai/mastra","slug":"azure-ad-token-error","errorCode":"AZURE_AD_TOKEN_ERROR","errorMessage":"Failed to get Azure AD token: ${response.status} ${error}","messagePattern":"Failed to get Azure AD token: (.+?) (.+?)","errorType":"http","errorClass":"MastraError","httpStatus":null,"severity":"error","filePath":"packages/core/src/llm/model/gateways/azure.ts","lineNumber":391,"sourceCode":"\n    const body = new URLSearchParams({\n      grant_type: 'client_credentials',\n      client_id: clientId,\n      client_secret: clientSecret,\n      scope: 'https://management.azure.com/.default',\n    });\n\n    const response = await fetch(tokenEndpoint, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/x-www-form-urlencoded',\n      },\n      body: body.toString(),\n    });\n\n    if (!response.ok) {\n      const error = await response.text();\n      throw new MastraError({\n        id: 'AZURE_AD_TOKEN_ERROR',\n        domain: 'LLM',\n        category: 'UNKNOWN',\n        text: `Failed to get Azure AD token: ${response.status} ${error}`,\n      });\n    }\n\n    const tokenResponse = (await response.json()) as AzureTokenResponse;\n\n    const expiresAt = Math.floor(Date.now() / 1000) + tokenResponse.expires_in;\n\n    await this.tokenCache.set(cacheKey, {\n      token: tokenResponse.access_token,\n      expiresAt,\n    });\n\n    return tokenResponse.access_token;\n  }","sourceCodeStart":373,"sourceCodeEnd":409,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/llm/model/gateways/azure.ts#L373-L409","documentation":"The gateway's OAuth client-credentials request to the Azure AD (Entra ID) token endpoint returned a non-OK HTTP response; the gateway wraps the status and response body in AZURE_AD_TOKEN_ERROR. This happens inside getAzureADToken, called by the token accessor, when Microsoft's identity platform rejects the token request.","triggerScenarios":"POST to https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token fails — e.g. 401 invalid_client (wrong clientId/secret), 400 invalid_request (bad tenantId or malformed body), 400 AADSTS700016 (app not found in tenant), or a proxy returning 403/502.","commonSituations":"Expired or rotated client secrets still referenced in env; client secret copied with whitespace/quotes; tenantId from a tenant where the app registration does not exist; corporate proxy blocking login.microsoftonline.com; requested scope not granted admin consent.","solutions":["Verify tenantId, clientId, and clientSecret are correct and current (App Registration > Certificates & secrets in the Azure portal).","Read the AADSTS error code in the message body — it names the exact cause (e.g. AADSTS7000215 invalid client secret).","Confirm the app registration exists in the specified tenant and the secret has not expired; create a new secret if needed.","Check network/proxy access to login.microsoftonline.com from the runtime environment.","Ensure the requested scope (e.g. https://cognitiveservices.azure.com/.default) is granted admin consent."],"exampleFix":"// before (stale secret)\nclientSecret: process.env.AZURE_CLIENT_SECRET // old value after rotation -> 401 invalid_client\n// after\nclientSecret: process.env.AZURE_CLIENT_SECRET // rotated value copied fresh from Certificates & secrets, trimmed","handlingStrategy":"try-catch","validationCode":"function assertAdCredentials(env: Record<string,string|undefined>) {\n  for (const k of ['AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET']) {\n    if (!env[k]?.trim()) throw new Error(`${k} is not set — AD token request would fail`);\n  }\n}\nassertAdCredentials(process.env);","typeGuard":null,"tryCatchPattern":"try {\n  const token = await gateway.token();\n} catch (e) {\n  if (e instanceof MastraError && e.id === 'AZURE_AD_TOKEN_ERROR') {\n    const aadsts = /AADSTS\\d+/.exec(e.message)?.[0];\n    console.error(`Azure AD token request failed (${aadsts ?? 'unknown'}); check tenantId/clientId/clientSecret and network access to login.microsoftonline.com`);\n    return null; // or fall back to apiKey auth\n  }\n  throw e;\n}","preventionTips":["Rotate client secrets on a schedule and update the secret store before expiry.","Trim whitespace/quotes when copying client secrets into env vars.","Verify outbound network access to login.microsoftonline.com from deployment environments (allowlist via proxies).","Watch for the AADSTS code in the error body — each code maps to a specific fixable cause (expired secret, wrong tenant, missing consent)."],"tags":["azure","authentication","oauth","entra-id","http"],"backgroundTag":"oauth-token-request-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}