Profiles·Public

@azure/identity

semver>=3.0.0 <5.0.0postconditions4functions4last verified2026-06-24coverage score100%

Postconditions: what we check

  • getToken · get-token-no-try-catch
    error
    Whencredential.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)
    ThrowsCredentialUnavailableError — 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-catch
    error
    WhenThe 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().
    ThrowsError("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
    Sources[5][6][7]
  • InteractiveBrowserCredential.authenticate · interactive-authenticate-no-try-catch
    warning
    WhenInteractiveBrowserCredential.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.
    ThrowsCredentialUnavailableError — 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
    Sources[8][7][4]
  • DeviceCodeCredential.authenticate · device-code-authenticate-no-try-catch
    warning
    WhenDeviceCodeCredential.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.
    ThrowsCredentialUnavailableError — 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
Source code

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)

Azure Authentication for JavaScript SDK

@azure/identity Troubleshooting Guide

@azure/identity GitHub Repository


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 errorResponse property with error (code) and errorDescription
  • Common trigger: wrong client secret, expired certificate, invalid tenant ID

SDK Version History

  • @azure/identity v4.x: Added WorkloadIdentityCredential, improved MSAL caching
  • @azure/identity v3.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

  1. Azure-hosted services using ManagedIdentityCredential (via DefaultAzureCredential) to authenticate to storage, Key Vault, or databases
  2. Node.js backends using ClientSecretCredential to call Microsoft Graph API for M365 integration
  3. 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