azure.identity.aio package

Credentials for asynchronous Azure SDK clients.

class azure.identity.aio.AuthorizationCodeCredential(tenant_id: str, client_id: str, authorization_code: str, redirect_uri: str, *, client_secret: str | None = None, **kwargs: Any)[source]

Authenticates by redeeming an authorization code previously obtained from Microsoft Entra ID.

See Microsoft Entra ID documentation for more information about the authentication flow.

Parameters:
  • tenant_id (str) – ID of the application’s Microsoft Entra tenant. Also called its “directory” ID.

  • client_id (str) – The application’s client ID

  • authorization_code (str) – The authorization code from the user’s log-in

  • redirect_uri (str) – The application’s redirect URI. Must match the URI used to request the authorization code.

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example “login.microsoftonline.com”, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds.

  • client_secret (str) – One of the application’s client secrets. Required only for web apps and web APIs.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

Example:

Create an AuthorizationCodeCredential.
from azure.identity.aio import AuthorizationCodeCredential

credential = AuthorizationCodeCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    authorization_code="<auth_code>",
    redirect_uri="<redirect_uri>",
)
async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Request an access token for scopes.

This method is called automatically by Azure SDK clients.

The first time this method is called, the credential will redeem its authorization code. On subsequent calls the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon redeeming the authorization code.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:

ClientAuthenticationError – authentication failed. The error’s message attribute gives a reason. Any error response from Microsoft Entra ID is available as the error’s response attribute.

class azure.identity.aio.AzureCliCredential(*, tenant_id: str = '', additionally_allowed_tenants: List[str] | None = None, process_timeout: int = 10)[source]

Authenticates by requesting a token from the Azure CLI.

This requires previously logging in to Azure via “az login”, and will use the CLI’s currently logged in identity.

Keyword Arguments:
  • tenant_id (str) – Optional tenant to include in the token request.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

  • process_timeout (int) – Seconds to wait for the Azure CLI process to respond. Defaults to 10 seconds.

Example:

Create an AzureCliCredential.
from azure.identity.aio import AzureCliCredential

credential = AzureCliCredential()
async close() None[source]

Calling this method is unnecessary

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Request an access token for scopes.

This method is called automatically by Azure SDK clients. Applications calling this method directly must also handle token caching because this credential doesn’t cache the tokens it acquires.

Parameters:

scopes (str) – desired scope for the access token. This credential allows only one scope per request. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – not used by this credential; any value provided will be ignored.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.AzureDeveloperCliCredential(*, tenant_id: str = '', additionally_allowed_tenants: List[str] | None = None, process_timeout: int = 10)[source]

Authenticates by requesting a token from the Azure Developer CLI.

Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy resources in Azure. It’s built on top of the Azure CLI and provides additional functionality specific to Azure developers. It allows users to authenticate as a user and/or a service principal against Microsoft Entra ID. The AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of the logged-in user or service principal in Azure Developer CLI. It acts as the Azure Developer CLI logged-in user or service principal and executes an Azure CLI command underneath to authenticate the application against Microsoft Entra ID.

To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the commands below:

  • Run “azd auth login” in Azure Developer CLI to authenticate interactively as a user.

  • Run “azd auth login –client-id ‘client_id’ –client-secret ‘client_secret’ –tenant-id ‘tenant_id’” to authenticate as a service principal.

You may need to repeat this process after a certain time period, depending on the refresh token validity in your organization. Generally, the refresh token validity period is a few weeks to a few months. AzureDeveloperCliCredential will prompt you to sign in again.

Keyword Arguments:
  • tenant_id (str) – Optional tenant to include in the token request.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

  • process_timeout (int) – Seconds to wait for the Azure Developer CLI process to respond. Defaults to 10 seconds.

Example:

Create an AzureDeveloperCliCredential.
from azure.identity.aio import AzureDeveloperCliCredential

credential = AzureDeveloperCliCredential()
async close() None[source]

Calling this method is unnecessary

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Request an access token for scopes.

This method is called automatically by Azure SDK clients. Applications calling this method directly must also handle token caching because this credential doesn’t cache the tokens it acquires.

Parameters:

scopes (str) – desired scope for the access token. This credential allows only one scope per request. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – not used by this credential; any value provided will be ignored.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.AzurePowerShellCredential(*, tenant_id: str = '', additionally_allowed_tenants: List[str] | None = None, process_timeout: int = 10)[source]

Authenticates by requesting a token from Azure PowerShell.

This requires previously logging in to Azure via “Connect-AzAccount”, and will use the currently logged in identity.

Keyword Arguments:
  • tenant_id (str) – Optional tenant to include in the token request.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

  • process_timeout (int) – Seconds to wait for the Azure PowerShell process to respond. Defaults to 10 seconds.

Example:

Create an AzurePowerShellCredential.
from azure.identity.aio import AzurePowerShellCredential

credential = AzurePowerShellCredential()
async close() None[source]

Calling this method is unnecessary

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Request an access token for scopes.

This method is called automatically by Azure SDK clients. Applications calling this method directly must also handle token caching because this credential doesn’t cache the tokens it acquires.

Parameters:

scopes (str) – desired scope for the access token. This credential allows only one scope per request. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – not used by this credential; any value provided will be ignored.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.CertificateCredential(tenant_id: str, client_id: str, certificate_path: str | None = None, **kwargs: Any)[source]

Authenticates as a service principal using a certificate.

The certificate must have an RSA private key, because this credential signs assertions using RS256. See Microsoft Entra ID documentation for more information on configuring certificate authentication.

Parameters:
  • tenant_id (str) – ID of the service principal’s tenant. Also called its ‘directory’ ID.

  • client_id (str) – The service principal’s client ID

  • certificate_path (str) – Path to a PEM-encoded certificate file including the private key. If not provided, certificate_data is required.

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example ‘login.microsoftonline.com’, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds.

  • certificate_data (bytes) – The bytes of a certificate in PEM format, including the private key

  • password (str or bytes) – The certificate’s password. If a unicode string, it will be encoded as UTF-8. If the certificate requires a different encoding, pass appropriately encoded bytes instead.

  • cache_persistence_options (TokenCachePersistenceOptions) – Configuration for persistent token caching. If unspecified, the credential will cache tokens in memory.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

Example:

Create a CertificateCredential.
from azure.identity.aio import CertificateCredential

credential = CertificateCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    certificate_path="<path to PEM/PKCS12 certificate>",
    password="<certificate password if necessary>",
)

# Certificate/private key byte data can also be passed directly
credential = CertificateCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    certificate_data=b"<cert data>",
)
async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken

Request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

  • enable_cae (bool) – indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.ChainedTokenCredential(*credentials: AsyncTokenCredential)[source]

A sequence of credentials that is itself a credential.

Its get_token() method calls get_token on each credential in the sequence, in order, returning the first valid token received.

Parameters:

credentials (AsyncTokenCredential) – credential instances to form the chain

Example:

Create a ChainedTokenCredential.
from azure.identity.aio import ChainedTokenCredential, EnvironmentCredential, AzureCliCredential

credential_chain = (
    # Try EnvironmentCredential first
    EnvironmentCredential(),
    # Fallback to Azure CLI if EnvironmentCredential fails
    AzureCliCredential(),
)
credential = ChainedTokenCredential(*credential_chain)
async close() None[source]

Close the transport sessions of all credentials in the chain.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Asynchronously request a token from each credential, in order, returning the first token received.

If no credential provides a token, raises azure.core.exceptions.ClientAuthenticationError with an error message from each credential.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:

ClientAuthenticationError – no credential in the chain provided a token

class azure.identity.aio.ClientAssertionCredential(tenant_id: str, client_id: str, func: Callable[[], str], **kwargs: Any)[source]

Authenticates a service principal with a JWT assertion.

This credential is for advanced scenarios. CertificateCredential has a more convenient API for the most common assertion scenario, authenticating a service principal with a certificate.

Parameters:
  • tenant_id (str) – ID of the principal’s tenant. Also called its “directory” ID.

  • client_id (str) – The principal’s client ID

  • func – A callable that returns a string assertion. The credential will call this every time it acquires a new token.

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example “login.microsoftonline.com”, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

Example:

Create a ClientAssertionCredential.
from azure.identity.aio import ClientAssertionCredential

def get_assertion():
    return "<client-assertion>"

credential = ClientAssertionCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    func=get_assertion,
)
async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken

Request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

  • enable_cae (bool) – indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.ClientSecretCredential(tenant_id: str, client_id: str, client_secret: str, **kwargs: Any)[source]

Authenticates as a service principal using a client secret.

Parameters:
  • tenant_id (str) – ID of the service principal’s tenant. Also called its ‘directory’ ID.

  • client_id (str) – The service principal’s client ID

  • client_secret (str) – One of the service principal’s client secrets

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example ‘login.microsoftonline.com’, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds.

  • cache_persistence_options (TokenCachePersistenceOptions) – Configuration for persistent token caching. If unspecified, the credential will cache tokens in memory.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

Example:

Create a ClientSecretCredential.
from azure.identity.aio import ClientSecretCredential

credential = ClientSecretCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    client_secret="<client_secret>",
)
async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken

Request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

  • enable_cae (bool) – indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.DefaultAzureCredential(**kwargs: Any)[source]

A default credential capable of handling most Azure SDK authentication scenarios.

The identity it uses depends on the environment. When an access token is needed, it requests one using these identities in turn, stopping when one provides a token:

  1. A service principal configured by environment variables. See EnvironmentCredential for more details.

  2. WorkloadIdentityCredential if environment variable configuration is set by the Azure workload identity webhook.

  3. An Azure managed identity. See ManagedIdentityCredential for more details.

  4. On Windows only: a user who has signed in with a Microsoft application, such as Visual Studio. If multiple identities are in the cache, then the value of the environment variable AZURE_USERNAME is used to select which identity to use. See SharedTokenCacheCredential for more details.

  5. The identity currently logged in to the Azure CLI.

  6. The identity currently logged in to Azure PowerShell.

  7. The identity currently logged in to the Azure Developer CLI.

This default behavior is configurable with keyword arguments.

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example ‘login.microsoftonline.com’, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds. Managed identities ignore this because they reside in a single cloud.

  • exclude_workload_identity_credential (bool) – Whether to exclude the workload identity from the credential. Defaults to False.

  • exclude_developer_cli_credential (bool) – Whether to exclude the Azure Developer CLI from the credential. Defaults to False.

  • exclude_cli_credential (bool) – Whether to exclude the Azure CLI from the credential. Defaults to False.

  • exclude_environment_credential (bool) – Whether to exclude a service principal configured by environment variables from the credential. Defaults to False.

  • exclude_powershell_credential (bool) – Whether to exclude Azure PowerShell. Defaults to False.

  • exclude_visual_studio_code_credential (bool) – Whether to exclude stored credential from VS Code. Defaults to True.

  • exclude_managed_identity_credential (bool) – Whether to exclude managed identity from the credential. Defaults to False.

  • exclude_shared_token_cache_credential (bool) – Whether to exclude the shared token cache. Defaults to False.

  • managed_identity_client_id (str) – The client ID of a user-assigned managed identity. Defaults to the value of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used.

  • workload_identity_client_id (str) – The client ID of an identity assigned to the pod. Defaults to the value of the environment variable AZURE_CLIENT_ID, if any. If not specified, the pod’s default identity will be used.

  • workload_identity_tenant_id (str) – Preferred tenant for WorkloadIdentityCredential. Defaults to the value of environment variable AZURE_TENANT_ID, if any.

  • shared_cache_username (str) – Preferred username for SharedTokenCacheCredential. Defaults to the value of environment variable AZURE_USERNAME, if any.

  • shared_cache_tenant_id (str) – Preferred tenant for SharedTokenCacheCredential. Defaults to the value of environment variable AZURE_TENANT_ID, if any.

  • visual_studio_code_tenant_id (str) – Tenant ID to use when authenticating with VisualStudioCodeCredential. Defaults to the “Azure: Tenant” setting in VS Code’s user settings or, when that setting has no value, the “organizations” tenant, which supports only Azure Active Directory work or school accounts.

  • process_timeout (int) – The timeout in seconds to use for developer credentials that run subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to 10 seconds.

Example:

Create a DefaultAzureCredential.
from azure.identity.aio import DefaultAzureCredential

credential = DefaultAzureCredential()
async close() None

Close the transport sessions of all credentials in the chain.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Asynchronously request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:

ClientAuthenticationError – authentication failed. The exception has a message attribute listing each authentication attempt and its error message.

class azure.identity.aio.EnvironmentCredential(**kwargs: Any)[source]

A credential configured by environment variables.

This credential is capable of authenticating as a service principal using a client secret or a certificate, or as a user with a username and password. Configuration is attempted in this order, using these environment variables:

Service principal with secret:
  • AZURE_TENANT_ID: ID of the service principal’s tenant. Also called its ‘directory’ ID.

  • AZURE_CLIENT_ID: the service principal’s client ID

  • AZURE_CLIENT_SECRET: one of the service principal’s client secrets

  • AZURE_AUTHORITY_HOST: authority of a Microsoft Entra endpoint, for example “login.microsoftonline.com”, the authority for Azure Public Cloud, which is the default when no value is given.

Service principal with certificate:
  • AZURE_TENANT_ID: ID of the service principal’s tenant. Also called its ‘directory’ ID.

  • AZURE_CLIENT_ID: the service principal’s client ID

  • AZURE_CLIENT_CERTIFICATE_PATH: path to a PEM or PKCS12 certificate file including the private key.

  • AZURE_CLIENT_CERTIFICATE_PASSWORD: (optional) password of the certificate file, if any.

  • AZURE_AUTHORITY_HOST: authority of a Microsoft Entra endpoint, for example “login.microsoftonline.com”, the authority for Azure Public Cloud, which is the default when no value is given.

Example:

Create an EnvironmentCredential.
from azure.identity.aio import EnvironmentCredential

credential = EnvironmentCredential()
async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Asynchronously request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:

CredentialUnavailableError – environment variable configuration is incomplete

class azure.identity.aio.ManagedIdentityCredential(**kwargs: Any)[source]

Authenticates with an Azure managed identity in any hosting environment which supports managed identities.

This credential defaults to using a system-assigned identity. To configure a user-assigned identity, use one of the keyword arguments. See Microsoft Entra ID documentation for more information about configuring managed identity for applications.

Keyword Arguments:
  • client_id (str) – a user-assigned identity’s client ID or, when using Pod Identity, the client ID of an Azure AD app registration. This argument is supported in all hosting environments.

  • identity_config (Mapping[str, str]) – a mapping {parameter_name: value} specifying a user-assigned identity by its object or resource ID, for example {"object_id": "..."}. Check the documentation for your hosting environment to learn what values it expects.

Example:

Create a ManagedIdentityCredential.
from azure.identity.aio import ManagedIdentityCredential

credential = ManagedIdentityCredential()

# Can also specify a client ID of a user-assigned managed identity
credential = ManagedIdentityCredential(
    client_id="<client_id>",
)
async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Asynchronously request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scope for the access token. This credential allows only one scope per request. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – not used by this credential; any value provided will be ignored.

  • tenant_id (str) – not used by this credential; any value provided will be ignored.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:

CredentialUnavailableError – managed identity isn’t available in the hosting environment

class azure.identity.aio.OnBehalfOfCredential(tenant_id: str, client_id: str, *, client_certificate: bytes | None = None, client_secret: str | None = None, user_assertion: str, **kwargs: Any)[source]

Authenticates a service principal via the on-behalf-of flow.

This flow is typically used by middle-tier services that authorize requests to other services with a delegated user identity. Because this is not an interactive authentication flow, an application using it must have admin consent for any delegated permissions before requesting tokens for them. See Microsoft Entra ID documentation for a more detailed description of the on-behalf-of flow.

Parameters:
  • tenant_id (str) – ID of the service principal’s tenant. Also called its “directory” ID.

  • client_id (str) – The service principal’s client ID

Keyword Arguments:
  • client_secret (str) – Optional. A client secret to authenticate the service principal. Either client_secret or client_certificate must be provided.

  • client_certificate (bytes) – Optional. The bytes of a certificate in PEM or PKCS12 format including the private key to authenticate the service principal. Either client_secret or client_certificate must be provided.

  • user_assertion (str) – Required. The access token the credential will use as the user assertion when requesting on-behalf-of tokens

  • authority (str) – Authority of a Microsoft Entra endpoint, for example “login.microsoftonline.com”, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds.

  • password (str or bytes) – A certificate password. Used only when client_certificate is provided. If this value is a unicode string, it will be encoded as UTF-8. If the certificate requires a different encoding, pass appropriately encoded bytes instead.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

Example:

Create an OnBehalfOfCredential.
from azure.identity.aio import OnBehalfOfCredential

credential = OnBehalfOfCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    client_secret="<client_secret>",
    user_assertion="<access_token>",
)
async close() None[source]
async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken

Request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

  • enable_cae (bool) – indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
class azure.identity.aio.SharedTokenCacheCredential(username: str | None = None, *, authority: str | None = None, tenant_id: str | None = None, **kwargs: Any)[source]

Authenticates using tokens in the local cache shared between Microsoft applications.

Parameters:

username (str) – Username (typically an email address) of the user to authenticate as. This is required because the local cache may contain tokens for multiple identities.

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example ‘login.microsoftonline.com’, the authority for Azure Public Cloud (which is the default). AzureAuthorityHosts defines authorities for other clouds.

  • tenant_id (str) – a Microsoft Entra tenant ID. Used to select an account when the cache contains tokens for multiple identities.

  • cache_persistence_options (TokenCachePersistenceOptions) – configuration for persistent token caching. If not provided, the credential will use the persistent cache shared by Microsoft development applications

async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken[source]

Get an access token for scopes from the shared cache.

If no access token is cached, attempt to acquire one using a cached refresh token.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

  • enable_cae (bool) – indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
  • CredentialUnavailableError – the cache is unavailable or contains insufficient user information

  • ClientAuthenticationError – authentication failed. The error’s message attribute gives a reason. Any error response from Microsoft Entra ID is available as the error’s response attribute.

static supported() bool

Whether the shared token cache is supported on the current platform.

Returns:

True if the shared token cache is supported on the current platform.

Return type:

bool

class azure.identity.aio.VisualStudioCodeCredential(**kwargs: Any)[source]

Authenticates as the Azure user signed in to Visual Studio Code via the ‘Azure Account’ extension.

It’s a known issue that this credential doesn’t work with Azure Account extension versions newer than 0.9.11. A long-term fix to this problem is in progress. In the meantime, consider authenticating with AzureCliCredential.

Keyword Arguments:
  • authority (str) – Authority of a Microsoft Entra endpoint, for example “login.microsoftonline.com”. This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority matching the “Azure: Cloud” setting in VS Code’s user settings or, when that setting has no value, the authority for Azure Public Cloud.

  • tenant_id (str) – ID of the tenant the credential should authenticate in. Defaults to the “Azure: Tenant” setting in VS Code’s user settings or, when that setting has no value, the “organizations” tenant, which supports only Microsoft Entra work or school accounts.

  • additionally_allowed_tenants (List[str]) – Specifies tenants in addition to the specified “tenant_id” for which the credential may acquire tokens. Add the wildcard value “*” to allow the credential to acquire tokens for any tenant the application can access.

async close() None[source]

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, **kwargs: Any) AccessToken[source]

Request an access token for scopes as the user currently signed in to Visual Studio Code.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:

CredentialUnavailableError – the credential cannot retrieve user details from Visual Studio Code

class azure.identity.aio.WorkloadIdentityCredential(*, tenant_id: str | None = None, client_id: str | None = None, token_file_path: str | None = None, **kwargs: Any)[source]

Authenticates using Microsoft Entra Workload ID.

Workload identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) to access other Azure resources without the need for a service principal or managed identity. With workload identity authentication, applications authenticate themselves using their own identity, rather than using a shared service principal or managed identity. Under the hood, workload identity authentication uses the concept of Service Account Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using workload identity authentication, you can avoid the need to manage and rotate service principals or managed identities for each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don’t need to worry about storing and securing sensitive credentials themselves.

The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires a token using the service account credentials available in the Azure Kubernetes environment. Refer to this workload identity overview for more information.

Keyword Arguments:
  • tenant_id (str) – ID of the application’s Microsoft Entra tenant. Also called its “directory” ID.

  • client_id (str) – The client ID of a Microsoft Entra app registration.

  • token_file_path (str) – The path to a file containing a Kubernetes service account token that authenticates the identity.

Example:

Create a WorkloadIdentityCredential.
from azure.identity.aio import WorkloadIdentityCredential

credential = WorkloadIdentityCredential(
    tenant_id="<tenant_id>",
    client_id="<client_id>",
    token_file_path="<token_file_path>",
)

# Parameters can be omitted if the following environment variables are set:
#   - AZURE_TENANT_ID
#   - AZURE_CLIENT_ID
#   - AZURE_FEDERATED_TOKEN_FILE
credential = WorkloadIdentityCredential()
async close() None

Close the credential’s transport session.

async get_token(*scopes: str, claims: str | None = None, tenant_id: str | None = None, enable_cae: bool = False, **kwargs: Any) AccessToken

Request an access token for scopes.

This method is called automatically by Azure SDK clients.

Parameters:

scopes (str) – desired scopes for the access token. This method requires at least one scope. For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.

Keyword Arguments:
  • claims (str) – additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – optional tenant to include in the token request.

  • enable_cae (bool) – indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Returns:

An access token with the desired scopes.

Return type:

AccessToken

Raises:
azure.identity.aio.get_bearer_token_provider(credential: AsyncTokenCredential, *scopes: str) Callable[[], Coroutine[Any, Any, str]][source]

Returns a callable that provides a bearer token.

It can be used for instance to write code like:

from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider

credential = DefaultAzureCredential()
bearer_token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")


# Usage
request.headers["Authorization"] = "Bearer " + await bearer_token_provider()
Parameters:
  • credential (AsyncTokenCredential) – The credential used to authenticate the request.

  • scopes (str) – The scopes required for the bearer token.

Return type:

coroutine

Returns:

A coroutine that returns a bearer token.