Introducing a new way to review your PRs.

Read the announcement

azure / azure-cli

Azure Command-Line Interface

View on GitHub

13 documents · Updated Nov 16, 2026

docs / core-auth-profile-cloud

Azure CLI Core Auth, Profile, Cloud, SDK Client, Environment, and Local Context

Overview

This doc covers the Azure CLI account and token flow owned by src/azure-cli-core/azure/cli/core/auth/**, src/…/_profile.py, src/…/cloud.py, src/…/credential_helper.py, src/…/local_context.py, src/…/_environment.py, src/azure-cli-core/azure/cli/core/sdk/**, src/azure-cli/azure/cli/command_modules/profile/**, and src/azure-cli/azure/cli/command_modules/cloud/**. The practical routing entry points are the az login/logout/account ... commands registered in src/…/__init__.py, the az cloud ... commands registered in src/…/__init__.py, and management-client creation through src/…/client_factory.py when commands need credentials.

src/…/custom.py is the command-facing layer for account state. login() validates mutually exclusive login modes, decodes --claims-challenge, builds service-principal credential input, handles Cloud Shell and managed identity shortcuts, and then calls Profile.login() in src/…/_profile.py. Interactive user login uses auth-code or device-code MSAL flows; username/password uses public-client password auth; service principal login uses confidential-client auth; managed identity and Cloud Shell use their dedicated credential wrappers. After a token is obtained, Profile.login() discovers subscriptions through SubscriptionFinder, normalizes them into profile dictionaries, writes them into the ACCOUNT session store, and persists the selected default subscription for the active cloud through set_cloud_subscription() in src/…/cloud.py. --skip-subscription-discovery avoids broad ARM subscription listing, optionally fetching one subscription by ID; --allow-no-subscriptions creates tenant-level accounts named N/A(tenant level account).

The local account model lives in src/…/_profile.py. Cached subscriptions are stored under subscriptions with stable keys such as id, name, tenantId, environmentName, isDefault, and nested user metadata. Profile.get_subscription() resolves the current or requested account from that cache; Profile.set_active_subscription() switches the default account only within the active cloud; Profile.refresh_accounts() re-runs subscription discovery per cached user or service principal and replaces the active-cloud account set. Profile.get_raw_token() backs az account get-access-token and returns the legacy tuple plus expiresOn; Profile.get_login_credentials() backs SDK clients and returns a CredentialAdaptor, subscription ID, and tenant ID, optionally adding auxiliary credentials for cross-tenant ARM calls.

MSAL integration is concentrated in src/…/identity.py and src/…/msal_credentials.py. Identity constructs MSAL authorities from cloud active_directory endpoints, chooses the CLI public client ID from src/…/constants.py, and lazily shares process-wide MSAL token cache, HTTP cache, and service-principal store instances. The token cache is stored under the Azure config directory as msal_token_cache.{bin,json}, service-principal entries as service_principal_entries.{bin,json}, and MSAL HTTP cache as msal_http_cache.bin; src/…/persistence.py selects encrypted OS persistence when configured and plaintext file persistence otherwise. ServicePrincipalAuth persists only service-principal credential material needed to reconstruct MSAL client credentials: client secret, certificate path plus SN+issuer option, or federated token assertion.

Credential wrappers in src/…/msal_credentials.py expose a common acquire_token(scopes, **kwargs) shape. UserCredential looks up a single account in MSAL cache and silently acquires tokens, relaunching interactive auth only for VM SSH certificate requests identified by data.token_type == 'ssh-cert'. ServicePrincipalCredential calls acquire_token_for_client; CloudShellCredential uses prompt-none interactive MSAL because Cloud Shell acts as its own broker; ManagedIdentityCredential uses MSAL's managed identity client and converts CLI scopes back to a resource. src/…/credential_adaptor.py adapts these wrappers to Track 2 SDK get_token() and get_token_info(), preserves only supported options (data and claims challenges), and can produce auxiliary tokens for x-ms-authorization-auxiliary.

Cloud metadata and selection are managed by src/…/cloud.py, with command wrappers in src/…/custom.py. Built-in clouds are represented as Cloud objects with CloudEndpoints and CloudSuffixes; custom clouds and per-cloud saved subscription IDs are serialized into ~/.azure/clouds.config (or the directory from AZURE_CONFIG_DIR). If ARM_CLOUD_METADATA_URL is set, get_known_clouds() fetches ARM metadata and caches converted endpoint definitions in cloudEndpoints.json; otherwise it uses the hard-coded public, China, US Gov, Bleu, and Delos clouds. az cloud register/update can auto-discover endpoints from {resource_manager}/metadata/endpoints?api-version=2022-09-01, then overlays explicit endpoint and suffix arguments. switch_active_cloud() writes the active cloud name to CLI config and attempts to select that cloud's remembered subscription or first enabled cached subscription.

SDK client creation pulls this auth and cloud state together in src/…/client_factory.py. When a management client is requested without an explicit credential, _get_mgmt_service_client() calls Profile.get_login_credentials(), binds the client base URL to cli_ctx.cloud.endpoints.resource_manager, and for Track 2 clients adds ARM challenge authentication with scopes derived from cli_ctx.cloud.endpoints.active_directory_resource_id. src/…/policies.py supplies the Track 2 policies used there: safe network tracing redacts Authorization and x-ms-authorization-auxiliary, user-agent telemetry records the final SDK user agent, and the optional custom hook can call ARM acquirePolicyToken before non-GET operations when cli_ctx.data requests policy gating.

Environment and local context behavior are intentionally small but affect where auth state is read. src/…/_environment.py makes AZURE_CONFIG_DIR the root for profile, cloud, token-cache, and legacy ADAL cleanup files, falling back to ~/.azure. src/…/local_context.py implements parameter persistence under a per-working-directory .azure/.local_context_<system-user> file only when the user-specific local_context config option is on; command arguments can be read from the nearest context file by walking command scopes from most-specific command name to all, and saved under configured scopes. src/…/credential_helper.py is separate from login: it lazily loads Microsoft security secret-masker patterns and detects, names, or redacts secrets in strings, JSON-like values, or files before sensitive output is shown.

Coupling

Risks

  • src/…/cloud.py raises CloudEndpointNotSetException and CloudSuffixNotSetException from __getattribute__ when endpoint or suffix attributes are None. A new code path that probes with hasattr() or directly logs endpoint objects can unexpectedly raise; use has_endpoint_set() or inspect .__dict__ when optional endpoints are valid.
  • src/…/binary_cache.py writes msal_http_cache.bin without a cross-process lock and explicitly tolerates corrupted, empty, or version-incompatible pickle files by discarding them on load. Changes that make HTTP-cache contents required for correctness would turn an intentionally best-effort cache into an auth reliability problem.
  • src/…/identity.py keeps MSAL token cache, HTTP cache, and service-principal store as class-level singletons. If tests or long-lived processes change AZURE_CONFIG_DIR, encryption settings, authority, or tenant assumptions after the first Identity is constructed, later identities can keep using earlier process-wide cache/store objects.
  • src/…/identity.py persists service-principal certificate credentials as expanded certificate file paths, not copied certificate contents. If the certificate file is moved or removed after az login --service-principal --certificate, later Profile.get_login_credentials() calls cannot reconstruct the confidential-client credential.
  • src/…/local_context.py writes parameter persistence files under the current working directory and deletes the containing .azure directory when empty. If the working directory is removed, recreated, or permission-restricted, local context is ignored or cleanup warnings are emitted rather than failing the command, so callers should not depend on persisted parameters for correctness-critical auth or cloud selection.