CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-identity

Microsoft Azure Identity Library providing authentication credentials for Azure SDK clients.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

advanced.mddocs/

Advanced Features

Advanced authentication features including authentication records for session persistence, token caching configuration, exception handling, utility functions, and authority host constants for different Azure clouds.

Capabilities

AuthenticationRecord

Non-secret account information that enables silent authentication and account caching. Returned by interactive credentials' authenticate() method and can be serialized for persistent storage.

class AuthenticationRecord:
    def __init__(
        self,
        tenant_id: str,
        client_id: str,
        authority: str,
        home_account_id: str,
        username: str
    ):
        """
        Create an AuthenticationRecord with account information.
        
        Args:
            tenant_id: ID of the tenant the account should authenticate in
            client_id: Client ID of the application which performed the original authentication
            authority: Authority host used to authenticate the account
            home_account_id: Unique identifier of the account
            username: User principal or service principal name of the account
            
        Note:
            AuthenticationRecords are typically created by calling authenticate() on
            interactive credentials, not by direct instantiation.
        """

    @property
    def authority(self) -> str:
        """The authority host used to authenticate the account."""

    @property  
    def client_id(self) -> str:
        """The client ID of the application which performed the original authentication."""

    @property
    def home_account_id(self) -> str:
        """A unique identifier of the account."""

    @property
    def tenant_id(self) -> str:
        """The tenant the account should authenticate in."""

    @property
    def username(self) -> str:
        """The user principal or service principal name of the account."""

    @classmethod
    def deserialize(cls, data: str) -> 'AuthenticationRecord':
        """
        Deserialize an AuthenticationRecord from JSON string.
        
        Args:
            data: JSON string containing serialized AuthenticationRecord
            
        Returns:
            AuthenticationRecord: Deserialized authentication record
            
        Raises:
            ValueError: Invalid JSON data or missing required fields
        """

    def serialize(self) -> str:
        """
        Serialize the AuthenticationRecord to JSON string.
        
        Returns:
            str: JSON representation of the authentication record
            
        Note:
            The serialized record contains only non-secret account information
            and can be safely stored in configuration files or databases.
        """

Usage Example:

from azure.identity import InteractiveBrowserCredential, AuthenticationRecord
import json

# Perform interactive authentication
credential = InteractiveBrowserCredential()
record = credential.authenticate(scopes=["https://graph.microsoft.com/.default"])

print(f"Authenticated user: {record.username}")
print(f"Tenant: {record.tenant_id}")
print(f"Authority: {record.authority}")

# Serialize for persistent storage
serialized = record.serialize()
with open("auth_record.json", "w") as f:
    f.write(serialized)

# Later, deserialize and reuse
with open("auth_record.json", "r") as f:
    serialized = f.read()

restored_record = AuthenticationRecord.deserialize(serialized)

# Create new credential with cached account info
cached_credential = InteractiveBrowserCredential(
    authentication_record=restored_record,
    disable_automatic_authentication=True  # Only use cache, don't prompt
)

try:
    token = cached_credential.get_token("https://graph.microsoft.com/.default")
    print("Silent authentication successful")
except AuthenticationRequiredError:
    print("Cache expired, interactive authentication required")

TokenCachePersistenceOptions

Configuration options for persistent token caching across application sessions. Enables tokens to be cached securely on disk and shared between application instances.

class TokenCachePersistenceOptions:
    def __init__(
        self,
        *,
        allow_unencrypted_storage: bool = False,
        name: str = "msal.cache",
        **kwargs
    ):
        """
        Create TokenCachePersistenceOptions for configuring persistent token caching.
        
        Args:
            allow_unencrypted_storage: Whether to fall back to unencrypted storage when
                encryption is not available (default: False for security)
            name: Prefix name of the cache for isolation between applications (default: "msal.cache")
            
        Security Note:
            When allow_unencrypted_storage=False and encryption is not available,
            the credential will not cache tokens persistently. This is the secure default.
        """

Usage Example:

from azure.identity import (
    ClientSecretCredential,
    TokenCachePersistenceOptions,
    InteractiveBrowserCredential
)

# Configure encrypted token caching
cache_options = TokenCachePersistenceOptions(
    allow_unencrypted_storage=False,  # Require encryption (secure default)
    name="myapp.cache"               # Isolate cache from other applications
)

# Use with service principal credential
sp_credential = ClientSecretCredential(
    tenant_id="your-tenant-id",
    client_id="your-client-id", 
    client_secret="your-client-secret",
    cache_persistence_options=cache_options
)

# Use with interactive credential  
interactive_credential = InteractiveBrowserCredential(
    cache_persistence_options=cache_options
)

# Development environment with unencrypted fallback (less secure)
dev_cache_options = TokenCachePersistenceOptions(
    allow_unencrypted_storage=True,   # Allow unencrypted storage if needed
    name="dev.cache"
)

dev_credential = InteractiveBrowserCredential(
    cache_persistence_options=dev_cache_options
)

Exception Handling

Comprehensive exception classes for handling authentication failures and providing appropriate fallback strategies.

from azure.core.exceptions import ClientAuthenticationError

class CredentialUnavailableError(ClientAuthenticationError):
    """
    The credential did not attempt to authenticate because required data or state is unavailable.
    
    This exception indicates that the credential cannot authenticate in the current environment,
    typically due to missing configuration, unavailable services, or platform limitations.
    """

class AuthenticationRequiredError(CredentialUnavailableError):
    def __init__(
        self,
        scopes: Iterable[str],
        message: Optional[str] = None,
        claims: Optional[str] = None,
        **kwargs
    ):
        """
        Interactive authentication is required to acquire a token.
        
        Args:
            scopes: Scopes requested during failed authentication
            message: Error message describing the authentication requirement
            claims: Additional claims required in next authentication attempt
        """

    @property
    def scopes(self) -> Iterable[str]:
        """Scopes requested during failed authentication."""

    @property  
    def claims(self) -> Optional[str]:
        """Additional claims required in next authentication."""

Usage Example:

from azure.identity import (
    DefaultAzureCredential,
    InteractiveBrowserCredential,
    CredentialUnavailableError,
    AuthenticationRequiredError
)
from azure.core.exceptions import ClientAuthenticationError

def robust_authentication():
    """Implement robust authentication with proper exception handling."""
    
    # Try DefaultAzureCredential first
    try:
        credential = DefaultAzureCredential()
        token = credential.get_token("https://graph.microsoft.com/.default")
        print("Automatic authentication successful")
        return credential
        
    except CredentialUnavailableError as e:
        print(f"Default authentication unavailable: {e}")
        
        # Fall back to interactive authentication
        try:
            interactive_credential = InteractiveBrowserCredential()
            token = interactive_credential.get_token("https://graph.microsoft.com/.default")
            print("Interactive authentication successful")
            return interactive_credential
            
        except AuthenticationRequiredError as e:
            print(f"Interactive authentication required for scopes: {list(e.scopes)}")
            if e.claims:
                print(f"Additional claims needed: {e.claims}")
            
            # Perform explicit authentication
            record = interactive_credential.authenticate(*e.scopes, claims=e.claims)
            print(f"Authentication completed for user: {record.username}")
            return interactive_credential
            
        except ClientAuthenticationError as e:
            print(f"Authentication failed: {e}")
            raise
            
    except Exception as e:
        print(f"Unexpected error: {e}")
        raise

# Use robust authentication
try:
    credential = robust_authentication()
    # Use credential with Azure SDK clients
except Exception as e:
    print(f"Could not establish authentication: {e}")

Authority Hosts and Constants

Constants for Microsoft Entra ID authority hosts across different Azure clouds and regions.

class AzureAuthorityHosts:
    """Constants for Microsoft Entra ID authority hosts in different Azure clouds."""
    
    AZURE_CHINA: str = "https://login.chinacloudapi.cn"
    """Authority host for Azure China cloud."""
    
    AZURE_GOVERNMENT: str = "https://login.microsoftonline.us"
    """Authority host for Azure Government cloud."""
    
    AZURE_PUBLIC_CLOUD: str = "https://login.microsoftonline.com"
    """Authority host for Azure Public cloud (default)."""
    
    AZURE_GERMANY: str = "https://login.microsoftonline.de"
    """Authority host for Azure Germany cloud (deprecated)."""

# Backward compatibility alias
KnownAuthorities = AzureAuthorityHosts

Usage Example:

from azure.identity import ClientSecretCredential, AzureAuthorityHosts

# Azure Public Cloud (default)
public_credential = ClientSecretCredential(
    tenant_id="your-tenant-id",
    client_id="your-client-id",
    client_secret="your-client-secret"
    # authority defaults to AzureAuthorityHosts.AZURE_PUBLIC_CLOUD
)

# Azure Government Cloud
gov_credential = ClientSecretCredential(
    tenant_id="your-gov-tenant-id",
    client_id="your-gov-client-id",
    client_secret="your-gov-client-secret",
    authority=AzureAuthorityHosts.AZURE_GOVERNMENT
)

# Azure China Cloud
china_credential = ClientSecretCredential(
    tenant_id="your-china-tenant-id", 
    client_id="your-china-client-id",
    client_secret="your-china-client-secret",
    authority=AzureAuthorityHosts.AZURE_CHINA
)

# Custom authority (for Azure AD B2C or custom domains)
custom_credential = ClientSecretCredential(
    tenant_id="your-tenant-id",
    client_id="your-client-id",
    client_secret="your-client-secret",
    authority="https://your-custom-authority.com"
)

Utility Functions

Helper functions for working with credentials and tokens in different scenarios.

from typing import Callable, Any, Coroutine
from azure.core.credentials import TokenCredential, AccessToken

def get_bearer_token_provider(credential: TokenCredential, *scopes: str) -> Callable[[], str]:
    """
    Returns a callable that provides a bearer token string for HTTP Authorization headers.
    
    Args:
        credential: The credential used to authenticate requests
        *scopes: The scopes required for the bearer token
        
    Returns:
        Callable that returns a bearer token string when invoked
        
    Usage:
        Use this function to create a token provider for HTTP clients that expect
        a callable returning a bearer token string for Authorization headers.
    """

# Async version in azure.identity.aio
def get_bearer_token_provider(credential: AsyncTokenCredential, *scopes: str) -> Callable[[], Coroutine[Any, Any, str]]:
    """
    Returns a callable that provides a bearer token string asynchronously.
    
    Args:
        credential: The async credential used to authenticate requests  
        *scopes: The scopes required for the bearer token
        
    Returns:
        Callable that returns a coroutine yielding a bearer token string
    """

Usage Example:

from azure.identity import DefaultAzureCredential, get_bearer_token_provider
import requests

# Create credential
credential = DefaultAzureCredential()

# Create bearer token provider for Microsoft Graph
graph_token_provider = get_bearer_token_provider(
    credential, 
    "https://graph.microsoft.com/.default"
)

# Use with HTTP requests
def make_graph_request(endpoint: str):
    token = graph_token_provider()
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"https://graph.microsoft.com/v1.0/{endpoint}", headers=headers)
    return response.json()

# Make Microsoft Graph API calls
user_data = make_graph_request("me")
print(f"User: {user_data.get('displayName')}")

# Use with different scopes for different services  
storage_token_provider = get_bearer_token_provider(
    credential,
    "https://storage.azure.com/.default"  
)

management_token_provider = get_bearer_token_provider(
    credential,
    "https://management.azure.com/.default"
)

Environment Variables Reference

Complete reference of environment variables used by azure-identity credentials.

class EnvironmentVariables:
    """Environment variable names used by various credentials."""
    
    # Core authentication variables
    AZURE_CLIENT_ID: str = "AZURE_CLIENT_ID"
    """Application client ID for service principal authentication."""
    
    AZURE_CLIENT_SECRET: str = "AZURE_CLIENT_SECRET" 
    """Client secret for service principal authentication."""
    
    AZURE_TENANT_ID: str = "AZURE_TENANT_ID"
    """Microsoft Entra tenant ID."""
    
    # Certificate authentication variables
    AZURE_CLIENT_CERTIFICATE_PATH: str = "AZURE_CLIENT_CERTIFICATE_PATH"
    """Path to certificate file for certificate-based authentication."""
    
    AZURE_CLIENT_CERTIFICATE_PASSWORD: str = "AZURE_CLIENT_CERTIFICATE_PASSWORD"
    """Password for encrypted certificate files."""
    
    # Username/password authentication variables
    AZURE_USERNAME: str = "AZURE_USERNAME"
    """Username for user authentication."""
    
    AZURE_PASSWORD: str = "AZURE_PASSWORD" 
    """Password for user authentication."""
    
    # Managed identity endpoint variables
    IDENTITY_ENDPOINT: str = "IDENTITY_ENDPOINT"
    """Managed identity endpoint URL."""
    
    IDENTITY_HEADER: str = "IDENTITY_HEADER"
    """Managed identity authentication header."""
    
    MSI_ENDPOINT: str = "MSI_ENDPOINT"
    """Legacy managed identity endpoint URL."""
    
    MSI_SECRET: str = "MSI_SECRET"
    """Legacy managed identity authentication secret."""
    
    # Workload identity variables
    AZURE_FEDERATED_TOKEN_FILE: str = "AZURE_FEDERATED_TOKEN_FILE"
    """Path to federated token file for workload identity."""
    
    # Authority and region settings
    AZURE_AUTHORITY_HOST: str = "AZURE_AUTHORITY_HOST"
    """Authority host override for authentication."""
    
    AZURE_REGIONAL_AUTHORITY_NAME: str = "AZURE_REGIONAL_AUTHORITY_NAME"
    """Regional authority name for multi-region scenarios."""

Environment Setup Example:

# Service principal with client secret
export AZURE_TENANT_ID="your-tenant-id"
export AZURE_CLIENT_ID="your-client-id"  
export AZURE_CLIENT_SECRET="your-client-secret"

# Service principal with certificate
export AZURE_TENANT_ID="your-tenant-id"
export AZURE_CLIENT_ID="your-client-id"
export AZURE_CLIENT_CERTIFICATE_PATH="/path/to/certificate.pem"
export AZURE_CLIENT_CERTIFICATE_PASSWORD="cert-password"

# User authentication
export AZURE_TENANT_ID="your-tenant-id" 
export AZURE_CLIENT_ID="your-public-client-id"
export AZURE_USERNAME="user@example.com"
export AZURE_PASSWORD="user-password"

# Workload identity (typically set by Kubernetes)
export AZURE_TENANT_ID="your-tenant-id"
export AZURE_CLIENT_ID="your-workload-client-id"
export AZURE_FEDERATED_TOKEN_FILE="/var/run/secrets/azure/tokens/azure-identity-token"

# Authority override for different clouds
export AZURE_AUTHORITY_HOST="https://login.microsoftonline.us"  # Azure Government

Advanced Configuration Patterns

Multi-Tenant Authentication

from azure.identity import ClientSecretCredential

# Multi-tenant application configuration
multi_tenant_credential = ClientSecretCredential(
    tenant_id="primary-tenant-id",
    client_id="your-client-id",
    client_secret="your-client-secret",
    additionally_allowed_tenants=["tenant-2-id", "tenant-3-id", "*"]  # "*" allows all tenants
)

# Request token for specific tenant
primary_token = multi_tenant_credential.get_token(
    "https://graph.microsoft.com/.default"
)

secondary_token = multi_tenant_credential.get_token(
    "https://graph.microsoft.com/.default",
    tenant_id="tenant-2-id"  # Override to specific tenant
)

Credential Performance Optimization

from azure.identity import DefaultAzureCredential, TokenCachePersistenceOptions

# Optimize DefaultAzureCredential for production
production_credential = DefaultAzureCredential(
    # Exclude credentials not needed in production
    exclude_cli_credential=True,
    exclude_powershell_credential=True,
    exclude_developer_cli_credential=True,
    exclude_visual_studio_code_credential=True,
    exclude_interactive_browser_credential=True,
    
    # Configure specific identity for production
    managed_identity_client_id="production-identity-client-id"
)

# Optimize for development with caching
cache_options = TokenCachePersistenceOptions(
    allow_unencrypted_storage=True,  # For development only
    name="dev-app-cache"
)

dev_credential = DefaultAzureCredential(
    exclude_managed_identity_credential=True,  # Skip in local dev
    cache_persistence_options=cache_options
)

Custom Authority and Instance Discovery

from azure.identity import ClientSecretCredential

# Custom authority with instance discovery disabled
custom_credential = ClientSecretCredential(
    tenant_id="your-tenant-id",
    client_id="your-client-id", 
    client_secret="your-client-secret",
    authority="https://custom.authority.com",
    disable_instance_discovery=True  # Skip authority validation
)

# Azure AD B2C configuration
b2c_credential = ClientSecretCredential(
    tenant_id="your-b2c-tenant.onmicrosoft.com",
    client_id="your-b2c-client-id",
    client_secret="your-b2c-client-secret", 
    authority="https://your-b2c-tenant.b2clogin.com",
    disable_instance_discovery=True
)

Install with Tessl CLI

npx tessl i tessl/pypi-azure-identity

docs

advanced.md

async.md

azure-platform.md

core-credentials.md

developer.md

index.md

interactive.md

service-principal.md

tile.json