Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Azure Identity client library for Python - version 1.23.1

  • 2025-07-15
Feedback

In this article

The Azure Identity library providesMicrosoft Entra ID (formerly Azure Active Directory) token authentication support across the Azure SDK. It provides a set ofTokenCredential/SupportsTokenInfo implementations, which can be used to construct Azure SDK clients that support Microsoft Entra token authentication.

Source code|Package (PyPI)|Package (Conda)|API reference documentation|Microsoft Entra ID documentation

Getting started

Install the package

Install Azure Identity with pip:

pip install azure-identity

Prerequisites

  • AnAzure subscription
  • Python 3.9 or a recent version of Python 3 (this library doesn't support end-of-life versions)

Authenticate during local development

When debugging and executing code locally, it's typical for developers to use their own accounts for authenticating calls to Azure services. The Azure Identity library supports authenticating through developer tools to simplify local development.

Authenticate via the Azure CLI

DefaultAzureCredential andAzureCliCredential can authenticate as the user signed in to theAzure CLI. To sign in to the Azure CLI, runaz login. On a system with a default web browser, the Azure CLI launches the browser to authenticate a user.

When no default browser is available,az login uses the device code authentication flow. This flow can also be selected manually by runningaz login --use-device-code.

Authenticate via the Azure Developer CLI

Developers coding outside of an IDE can also use theAzure Developer CLI to authenticate. Applications usingDefaultAzureCredential orAzureDeveloperCliCredential can then use this account to authenticate calls in their application when running locally.

To authenticate with theAzure Developer CLI, run the commandazd auth login. For users running on a system with a default web browser, the Azure Developer CLI launches the browser to authenticate the user.

For systems without a default web browser, theazd auth login --use-device-code command uses the device code authentication flow.

Authenticate via Azure PowerShell

Developers coding outside of an IDE can also useAzure PowerShell to authenticate. Applications usingDefaultAzureCredential orAzurePowerShellCredential can then use this account to authenticate calls in their application when running locally.

To authenticate with Azure PowerShell, run theConnect-AzAccount cmdlet. By default, like the Azure CLI,Connect-AzAccount launches the default web browser to authenticate the user. For systems without a default web browser, theConnect-AzAccount uses the device code authentication flow. The user can also force Azure PowerShell to use the device code flow rather than launching a browser by specifying the-UseDeviceAuthentication argument.

Key concepts

Credentials

A credential is a class that contains or can obtain the data needed for a service client to authenticate requests. Service clients across the Azure SDK accept a credential instance when they're constructed, and use that credential to authenticate requests.

The Azure Identity library focuses on OAuth authentication with Microsoft Entra ID. It offers various credential classes capable of acquiring a Microsoft Entra access token. See theCredential classes section for a list of this library's credential classes.

DefaultAzureCredential

DefaultAzureCredential simplifies authentication while developing apps that deploy to Azure by combining credentials used in Azure hosting environments with credentials used in local development. For more information, seeDefaultAzureCredential overview.

Continuation policy

As of version 1.14.0,DefaultAzureCredential attempts to authenticate with all developer credentials until one succeeds, regardless of any errors previous developer credentials experienced. For example, a developer credential may attempt to get a token and fail, soDefaultAzureCredential will continue to the next credential in the flow. Deployed service credentials stop the flow with a thrown exception if they're able to attempt token retrieval, but don't receive one. Prior to version 1.14.0, developer credentials would similarly stop the authentication flow if token retrieval failed, but this is no longer the case.

This allows for trying all of the developer credentials on your machine while having predictable deployed behavior.

Examples

The following examples are provided:

Authenticate withDefaultAzureCredential

More details on configuring your environment to useDefaultAzureCredential can be found in the class'sreference documentation.

This example demonstrates authenticating theBlobServiceClient from theazure-storage-blob library usingDefaultAzureCredential.

from azure.identity import DefaultAzureCredentialfrom azure.storage.blob import BlobServiceClientdefault_credential = DefaultAzureCredential()client = BlobServiceClient(account_url, credential=default_credential)

Enable interactive authentication withDefaultAzureCredential

By default, interactive authentication is disabled inDefaultAzureCredential and can be enabled with a keyword argument:

DefaultAzureCredential(exclude_interactive_browser_credential=False)

When enabled,DefaultAzureCredential falls back to interactively authenticating via the system's default web browser when no other credential is available.

Specify a user-assigned managed identity withDefaultAzureCredential

Many Azure hosts allow the assignment of a user-assigned managed identity. To configureDefaultAzureCredential to authenticate a user-assigned managed identity, use themanaged_identity_client_id keyword argument:

DefaultAzureCredential(managed_identity_client_id=client_id)

Alternatively, set the environment variableAZURE_CLIENT_ID to the identity's client ID.

Define a custom authentication flow withChainedTokenCredential

WhileDefaultAzureCredential is generally the quickest way to authenticate apps for Azure, you can create a customized chain of credentials to be considered.ChainedTokenCredential enables users to combine multiple credential instances to define a customized chain of credentials. For more information, seeChainedTokenCredential overview.

Async credentials

This library includes a set of async APIs. To use the async credentials inazure.identity.aio, you must first install an async transport, such asaiohttp. For more information, seeazure-core documentation.

Async credentials should be closed when they're no longer needed. Each async credential is an async context manager and defines an asyncclose method. For example:

from azure.identity.aio import DefaultAzureCredential# call close when the credential is no longer neededcredential = DefaultAzureCredential()...await credential.close()# alternatively, use the credential as an async context managercredential = DefaultAzureCredential()async with credential:  ...

This example demonstrates authenticating the asynchronousSecretClient fromazure-keyvault-secrets with an asynchronous credential.

from azure.identity.aio import DefaultAzureCredentialfrom azure.keyvault.secrets.aio import SecretClientdefault_credential = DefaultAzureCredential()client = SecretClient("https://my-vault.vault.azure.net", default_credential)

Managed identity support

Managed identity authentication is supported via eitherDefaultAzureCredential orManagedIdentityCredential directly for the following Azure services:

Examples

These examples demonstrate authenticatingSecretClient from theazure-keyvault-secrets library withManagedIdentityCredential.

Authenticate with a user-assigned managed identity

To authenticate with a user-assigned managed identity, you must specify one of the following IDs for the managed identity.

Client ID
from azure.identity import ManagedIdentityCredentialfrom azure.keyvault.secrets import SecretClientcredential = ManagedIdentityCredential(client_id="managed_identity_client_id")client = SecretClient("https://my-vault.vault.azure.net", credential)
Resource ID
from azure.identity import ManagedIdentityCredentialfrom azure.keyvault.secrets import SecretClientresource_id = "/subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<mi-name>"credential = ManagedIdentityCredential(identity_config={"resource_id": resource_id})client = SecretClient("https://my-vault.vault.azure.net", credential)
Object ID
from azure.identity import ManagedIdentityCredentialfrom azure.keyvault.secrets import SecretClientcredential = ManagedIdentityCredential(identity_config={"object_id": "managed_identity_object_id"})client = SecretClient("https://my-vault.vault.azure.net", credential)

Authenticate with a system-assigned managed identity

from azure.identity import ManagedIdentityCredentialfrom azure.keyvault.secrets import SecretClientcredential = ManagedIdentityCredential()client = SecretClient("https://my-vault.vault.azure.net", credential)

Cloud configuration

Credentials default to authenticating to the Microsoft Entra endpoint for Azure Public Cloud. To access resources in other clouds, such as Azure Government or a private cloud, configure credentials with theauthority argument.AzureAuthorityHosts defines authorities for well-known clouds:

from azure.identity import AzureAuthorityHostsDefaultAzureCredential(authority=AzureAuthorityHosts.AZURE_GOVERNMENT)

If the authority for your cloud isn't listed inAzureAuthorityHosts, you can explicitly specify its URL:

DefaultAzureCredential(authority="https://login.partner.microsoftonline.cn")

As an alternative to specifying theauthority argument, you can also set theAZURE_AUTHORITY_HOST environment variable to the URL of your cloud's authority. This approach is useful when configuring multiple credentials to authenticate to the same cloud:

AZURE_AUTHORITY_HOST=https://login.partner.microsoftonline.cn

Not all credentials require this configuration. Credentials that authenticate through a development tool, such asAzureCliCredential, use that tool's configuration.

Credential classes

Credential chains

CredentialUsage
DefaultAzureCredentialProvides a simplified authentication experience to quickly start developing applications run in Azure.
ChainedTokenCredentialAllows users to define custom authentication flows composing multiple credentials.

Authenticate Azure-hosted applications

CredentialUsage
EnvironmentCredentialAuthenticates a service principal or user via credential information specified in environment variables.
ManagedIdentityCredentialAuthenticates the managed identity of an Azure resource.
WorkloadIdentityCredentialSupportsMicrosoft Entra Workload ID on Kubernetes.

Authenticate service principals

CredentialUsageReference
AzurePipelinesCredentialSupportsMicrosoft Entra Workload ID on Azure Pipelines.
CertificateCredentialAuthenticates a service principal using a certificate.Service principal authentication
ClientAssertionCredentialAuthenticates a service principal using a signed client assertion.
ClientSecretCredentialAuthenticates a service principal using a secret.Service principal authentication

Authenticate users

CredentialUsageReferenceNotes
AuthorizationCodeCredentialAuthenticates a user with a previously obtained authorization code.OAuth2 authentication code
DeviceCodeCredentialInteractively authenticates a user on devices with limited UI.Device code authentication
InteractiveBrowserCredentialInteractively authenticates a user with the default system browser.OAuth2 authentication codeInteractiveBrowserCredential doesn't support GitHub Codespaces. As a workaround, useDeviceCodeCredential.
OnBehalfOfCredentialPropagates the delegated user identity and permissions through the request chain.On-behalf-of authentication

Authenticate via development tools

CredentialUsageReference
AzureCliCredentialAuthenticates in a development environment with the Azure CLI.Azure CLI authentication
AzureDeveloperCliCredentialAuthenticates in a development environment with the Azure Developer CLI.Azure Developer CLI Reference
AzurePowerShellCredentialAuthenticates in a development environment with the Azure PowerShell.Azure PowerShell authentication

Environment variables

DefaultAzureCredential andEnvironmentCredential can be configured with environment variables. Each type of authentication requires values for specificvariables:

Service principal with secret

Variable nameValue
AZURE_CLIENT_IDID of a Microsoft Entra application
AZURE_TENANT_IDID of the application's Microsoft Entra tenant
AZURE_CLIENT_SECRETone of the application's client secrets

Service principal with certificate

Variable nameValueRequired
AZURE_CLIENT_IDID of a Microsoft Entra applicationX
AZURE_TENANT_IDID of the application's Microsoft Entra tenantX
AZURE_CLIENT_CERTIFICATE_PATHpath to a PEM or PKCS12 certificate file including private keyX
AZURE_CLIENT_CERTIFICATE_PASSWORDpassword of the certificate file, if any
AZURE_CLIENT_SEND_CERTIFICATE_CHAINIfTrue, the credential sends the public certificate chain in the x5c header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. Defaults to False. There's aknown limitation that async SNI authentication isn't supported.

Configuration is attempted in the preceding order. For example, if values for a client secret and certificate are both present, the client secret is used.

Continuous Access Evaluation

As of version 1.14.0, accessing resources protected byContinuous Access Evaluation (CAE) is possible on a per-request basis. This behavior can be enabled by setting theenable_cae keyword argument toTrue in the credential'sget_token method. CAE isn't supported for developer and managed identity credentials.

Token caching

Token caching is a feature provided by the Azure Identity library that allows apps to:

  • Cache tokens in memory (default) or on disk (opt-in).
  • Improve resilience and performance.
  • Reduce the number of requests made to Microsoft Entra ID to obtain access tokens.

The Azure Identity library offers both in-memory and persistent disk caching. For more information, see thetoken caching documentation.

Brokered authentication

An authentication broker is an application that runs on a user’s machine and manages the authentication handshakes and token maintenance for connected accounts. Currently, only the Windows Web Account Manager (WAM) is supported. To enable support, use theazure-identity-broker package. For details on authenticating using WAM, see thebroker plugin documentation.

Troubleshooting

See thetroubleshooting guide for details on how to diagnose various failure scenarios.

Error handling

Credentials raiseCredentialUnavailableError when they're unable to attempt authentication because they lack required data or state. For example,EnvironmentCredential raises this exception whenits configuration is incomplete.

Credentials raiseazure.core.exceptions.ClientAuthenticationError when they fail to authenticate.ClientAuthenticationError has amessage attribute, which describes why authentication failed. When raised byDefaultAzureCredential orChainedTokenCredential, the message collects error messages from each credential in the chain.

For more information on handling specific Microsoft Entra ID errors, see the Microsoft Entra IDerror code documentation.

Logging

This library uses the standardlogging library for logging. Credentials log basic information, including HTTP sessions (URLs, headers, etc.) at INFO level. These log entries don't contain authentication secrets.

Detailed DEBUG-level logging, including request/response bodies and header values, isn't enabled by default. It can be enabled with thelogging_enable argument. For example:

credential = DefaultAzureCredential(logging_enable=True)

CAUTION: DEBUG-level logs from credentials contain sensitive information.These logs must be protected to avoid compromising account security.

Next steps

Client library support

Client and management libraries listed on theAzure SDK release page that support Microsoft Entra authentication accept credentials from this library. You can learn more about using these libraries in their documentation, which is linked from the release page.

Known issues

This library doesn't supportAzure AD B2C.

For other open issues, refer to the library'sGitHub repository.

Provide feedback

If you encounter bugs or have suggestions,open an issue.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visithttps://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You'll only need to do this once across all repos using our CLA.

This project has adopted theMicrosoft Open Source Code of Conduct. For more information, see theCode of Conduct FAQ or contactopencode@microsoft.com with any additional questions or comments.

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo