@azure/identity
semver
>=3.0.0 <5.0.0postconditions4functions4last verified2026-06-24coverage score100%Postconditions: what we check
- getToken · get-token-no-try-catcherrorWhencredential.getToken() called without try-catch wrapping the await expression, where credential is an instance of any @azure/identity credential class (DefaultAzureCredential, ClientSecretCredential, ManagedIdentityCredential, WorkloadIdentityCredential, ClientCertificateCredential, or any class implementing TokenCredential from this package)Throws
CredentialUnavailableError — thrown by DefaultAzureCredential and ManagedIdentityCredential when no valid credential source is available (e.g., not running in Azure, no environment variables configured, no Azure CLI logged in). Message describes which sources were tried. AuthenticationError — thrown when a credential source is found but authentication fails. Contains errorResponse property with Azure AD error details: error code (e.g., "invalid_client", "AADSTS700016"), error description, and correlation ID. Common causes: wrong tenant ID, invalid or expired client secret, certificate errors, federated credential mismatch. CredentialUnavailableChainedError — thrown by ChainedTokenCredential when all credentials in the chain fail with CredentialUnavailableError. NetworkError / FetchError — connection timeout or DNS failure when reaching Azure AD endpoints (login.microsoftonline.com).Required handlingMUST wrap await credential.getToken() in try-catch. Catch block SHOULD distinguish CredentialUnavailableError (configuration issue — check environment variables, managed identity assignment, Azure CLI login) from AuthenticationError (credential found but auth failed — check tenant ID, client secret, certificate validity, federated credential config). For service-to-service authentication, a failed getToken() should surface to the caller or trigger an alert; it should not be silently swallowed.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - getBearerTokenProvider · bearer-token-provider-no-try-catcherrorWhenThe callback returned by getBearerTokenProvider() is called with `await` but is not wrapped in a try-catch block. This includes patterns like: `const token = await getToken()` or `headers.Authorization = 'Bearer ' + await getToken()` where getToken is the callback from getBearerTokenProvider().Throws
Error("Failed to get access token") — thrown by the callback when the underlying credential.getToken() fails to produce a valid token. Internally, the callback pipes through a bearer token policy and reads the Authorization header. If the credential throws (CredentialUnavailableError, AuthenticationError) or returns null, the header is empty and the callback throws this generic Error. CredentialUnavailableError — propagates from the underlying credential (DefaultAzureCredential, ManagedIdentityCredential) when no credential source is configured or when not running in a valid Azure environment. AuthenticationError — propagates from ClientSecretCredential or ClientCertificateCredential when the credential configuration is wrong (invalid tenant ID, expired secret, certificate mismatch).Required handlingMUST wrap calls to the getBearerTokenProvider() callback in try-catch. Log the specific error type — CredentialUnavailableError indicates configuration/environment issues; AuthenticationError indicates credential validity issues (rotate secrets, check certificate).costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - InteractiveBrowserCredential.authenticate · interactive-authenticate-no-try-catchwarningWhenInteractiveBrowserCredential.authenticate() is called with `await` but is not wrapped in a try-catch block. Pattern: `const record = await credential.authenticate(scopes)` where credential is an instance of InteractiveBrowserCredential.Throws
CredentialUnavailableError — thrown with details of the failure when authentication fails (browser popup blocked, user cancelled, redirect misconfigured, Azure App Registration missing "Mobile and desktop applications" redirect URI for Node.js use). AuthenticationError — thrown when the OAuth 2.0 flow completes but Azure AD rejects the authorization (consent not granted, conditional access policy blocking, MFA required but not completed). AuthenticationRequiredError — thrown when the token cannot be retrieved silently and user interaction is required but has been disabled via disableAutomaticAuthentication option.Required handlingMUST wrap await credential.authenticate() in try-catch. MUST check if the returned AuthenticationRecord is defined before using it (the return type is `AuthenticationRecord | undefined`). Do not use non-null assertion (!) on the return value.costlowin prodimmediate exceptionusers seeauthentication failurevisibilityvisible - DeviceCodeCredential.authenticate · device-code-authenticate-no-try-catchwarningWhenDeviceCodeCredential.authenticate() is called with `await` but is not wrapped in a try-catch block. Pattern: `const record = await credential.authenticate(scopes)` where credential is an instance of DeviceCodeCredential.Throws
CredentialUnavailableError — thrown with details of the failure when the device code flow cannot complete. Common causes: user did not enter the code at https://microsoft.com/devicelogin before the device code expired (default 15 min), tenant blocked device code flow via conditional access policy, or the App Registration is not configured to allow public-client device code grants. AuthenticationError — thrown when the OAuth 2.0 device code exchange completes but Azure AD rejects the authorization (consent not granted, conditional access blocking, MFA required but not satisfied, user account disabled). AuthenticationRequiredError — thrown when the token cannot be retrieved silently and user interaction is required but has been disabled via the `disableAutomaticAuthentication` option on the underlying msalClient (rare; authenticate() forces interaction by default).Required handlingMUST wrap await credential.authenticate() in try-catch. MUST check if the returned AuthenticationRecord is defined before using it (the return type is `AuthenticationRecord | undefined`). Do not use non-null assertion (!) on the return value. For CLI tools, surface the specific error type to the user — device code expiry, conditional access blocks, and tenant misconfiguration each have different remediation paths.costlowin prodimmediate exceptionusers seeauthentication failurevisibilityvisible
Sources
Every postcondition cites at least one of these. Grouped by source type; numbered to match the footnotes above.
Official documentation
- [1]learn.microsoft.com/en-us/javascript/apiIdentity Readme
- [2]learn.microsoft.com/en-us/azure/developerOverview
- [6]learn.microsoft.com/en-us/javascript/apiGetbearertokenprovider
- [7]learn.microsoft.com/en-us/javascript/apiIdentity
- [8]learn.microsoft.com/en-us/javascript/apiInteractivebrowsercredential
- [9]learn.microsoft.com/en-us/javascript/apiDevicecodecredential
- [11]learn.microsoft.com/en-us/entra/identity-platformV2 Oauth2 Device Code
Source code
- [3]github.com/Azure/azure-sdk-for-js/blobAzure/azure-sdk-for-js · TROUBLESHOOTING.md
- [4]github.com/Azure/azure-sdk-for-js/treeAzure/azure-sdk-for-js · identity
- [5]github.com/Azure/azure-sdk-for-js/blobAzure/azure-sdk-for-js · tokenProvider.ts
- [10]github.com/Azure/azure-sdk-for-js/blobAzure/azure-sdk-for-js · deviceCodeCredential.ts
Research notes
Curator notes from SOURCES.md captured when the profile was written so you can verify the reasoning, not just the rules.
Sources: @azure/identity
All behavioral claims in contract.yaml are derived from the following sources.
Official Microsoft Documentation
Azure Identity README (JavaScript SDK)
- URL: https://learn.microsoft.com/en-us/javascript/api/overview/azure/identity-readme
- Relevance: Authoritative overview of all credential classes, the TokenCredential interface, getToken() signature, and error types (CredentialUnavailableError, AuthenticationError).
Azure Authentication for JavaScript SDK
- URL: https://learn.microsoft.com/en-us/azure/developer/javascript/sdk/authentication/overview
- Relevance: Documents best practices for authentication, notes that all credential.getToken() calls are async and network-dependent, and recommends wrapping in try-catch.
@azure/identity Troubleshooting Guide
- URL: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/identity/identity/TROUBLESHOOTING.md
- Key claim: Documents CredentialUnavailableError (no valid credential source), AuthenticationError (AAD returned error response), and CredentialUnavailableChainedError (all chain entries failed).
@azure/identity GitHub Repository
- URL: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/identity/identity
- Relevance: Source of truth for TypeScript types, exported error classes, and credential implementations.
Error Type Documentation
CredentialUnavailableError
- Thrown by DefaultAzureCredential and ManagedIdentityCredential when no credential source is available
- Indicates configuration/environment issue (not wrong credentials — no credentials at all)
- Common trigger: deploying outside Azure without environment variables set
AuthenticationError
- Thrown when Azure AD / Entra ID returns an error response
- Contains
errorResponseproperty witherror(code) anderrorDescription - Common trigger: wrong client secret, expired certificate, invalid tenant ID
SDK Version History
@azure/identityv4.x: Added WorkloadIdentityCredential, improved MSAL caching@azure/identityv3.x: Stable DefaultAzureCredential chain, AzureDeveloperCliCredential added- All 3.x and 4.x versions: Same
getToken()signature and error types
Contract covers semver range ^3.0.0.
Real-World Usage Context
Common SaaS patterns using @azure/identity
- Azure-hosted services using ManagedIdentityCredential (via DefaultAzureCredential) to authenticate to storage, Key Vault, or databases
- Node.js backends using ClientSecretCredential to call Microsoft Graph API for M365 integration
- CI/CD pipelines using WorkloadIdentityCredential for federated access
All patterns share the same getToken() call and the same error behavior.
Error Handling Best Practice (from official docs)
import {
DefaultAzureCredential,
CredentialUnavailableError,
AuthenticationError,
} from '@azure/identity';
const credential = new DefaultAzureCredential();
try {
const token = await credential.getToken('https://storage.azure.com/.default');
// token.token is the Bearer token string
} catch (err) {
if (err instanceof CredentialUnavailableError) {
// No credential source configured
// Check: managed identity, env vars (AZURE_CLIENT_ID etc.), Azure CLI
console.error('No Azure credential available:', err.message);
} else if (err instanceof AuthenticationError) {
// Credential found but auth failed
// Check: tenant ID, client secret expiry, certificate validity
console.error('Azure auth failed:', err.errorResponse?.errorDescription);
} else {
// Network error, unexpected failure
console.error('getToken() unexpected error:', err);
}
throw err;
}
Source: https://learn.microsoft.com/en-us/javascript/api/overview/azure/identity-readme#credential-classes
Need a different package?
Request a profile