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

developer.mddocs/

Developer Tool Credentials

Authenticate using existing Azure developer tool sessions including Azure CLI, Azure PowerShell, Azure Developer CLI, and Visual Studio Code. These credentials enable seamless local development by leveraging existing authenticated sessions from developer tools.

Capabilities

AzureCliCredential

Authenticates by requesting tokens from the Azure CLI. Uses the account currently signed in via az login command, providing seamless authentication for local development without additional configuration.

class AzureCliCredential:
    def __init__(
        self,
        *,
        process_timeout: int = 10,
        **kwargs
    ):
        """
        Create an AzureCliCredential that uses the Azure CLI for authentication.
        
        Args:
            process_timeout: Seconds to wait for the Azure CLI process to complete (default: 10)
            
        Requirements:
            - Azure CLI must be installed and available in PATH
            - User must be signed in via 'az login'
            - Azure CLI version 2.0.12 or later
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token from Azure CLI.
        
        Args:
            *scopes: Desired scopes for the access token
            claims: Additional claims required in the token (not supported by Azure CLI)
            tenant_id: Optional tenant ID override (will switch Azure CLI context)
            
        Returns:
            AccessToken: The access token with expiration information
            
        Raises:
            CredentialUnavailableError: Azure CLI not installed, not logged in, or process failed
            ClientAuthenticationError: Azure CLI returned invalid token response
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information from Azure CLI.
        
        Args:
            *scopes: Desired scopes for the access token
            options: Additional options for token acquisition
            
        Returns:
            dict: Token information including access token and metadata
        """

Usage Example:

from azure.identity import AzureCliCredential
from azure.identity import CredentialUnavailableError

try:
    # Use current Azure CLI session
    credential = AzureCliCredential()
    
    # Test authentication
    token = credential.get_token("https://management.azure.com/.default")
    print("Azure CLI authentication successful")
    
except CredentialUnavailableError as e:
    print("Azure CLI not available. Please run 'az login'")
    print(f"Error: {e}")

# Use with Azure SDK clients
from azure.mgmt.resource import ResourceManagementClient

resource_client = ResourceManagementClient(
    credential=AzureCliCredential(),
    subscription_id="your-subscription-id"
)

# List resource groups using CLI authentication
for rg in resource_client.resource_groups.list():
    print(f"Resource Group: {rg.name}")

# Custom timeout for slow CLI operations
slow_credential = AzureCliCredential(process_timeout=30)

Azure CLI Setup:

# Install Azure CLI
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# Sign in to Azure
az login

# Sign in with specific tenant
az login --tenant your-tenant-id

# Set default subscription
az account set --subscription "your-subscription-id"

# Verify current account
az account show

AzureDeveloperCliCredential

Authenticates by requesting tokens from the Azure Developer CLI (azd). Uses the account currently signed in via azd auth login, enabling authentication for Azure Developer CLI workflows and cloud-native application development.

class AzureDeveloperCliCredential:
    def __init__(
        self,
        *,
        process_timeout: int = 10,
        **kwargs
    ):
        """
        Create an AzureDeveloperCliCredential that uses the Azure Developer CLI for authentication.
        
        Args:
            process_timeout: Seconds to wait for the Azure Developer CLI process to complete (default: 10)
            
        Requirements:
            - Azure Developer CLI (azd) must be installed and available in PATH
            - User must be signed in via 'azd auth login'
            - Azure Developer CLI version 0.4.0 or later
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token from Azure Developer CLI.
        
        Args:
            *scopes: Desired scopes for the access token
            claims: Additional claims required in the token (not supported by Azure Developer CLI)
            tenant_id: Optional tenant ID override
            
        Returns:
            AccessToken: The access token with expiration information
            
        Raises:
            CredentialUnavailableError: Azure Developer CLI not installed, not logged in, or process failed
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information from Azure Developer CLI.
        
        Args:
            *scopes: Desired scopes for the access token
            options: Additional options for token acquisition
            
        Returns:
            dict: Token information including access token and metadata
        """

Usage Example:

from azure.identity import AzureDeveloperCliCredential

# Use Azure Developer CLI authentication
credential = AzureDeveloperCliCredential()

# Use with Azure SDK for cloud-native development
from azure.storage.blob import BlobServiceClient

blob_client = BlobServiceClient(
    account_url="https://account.blob.core.windows.net",
    credential=credential
)

# Deploy application resources using azd authentication
from azure.mgmt.containerinstance import ContainerInstanceManagementClient

container_client = ContainerInstanceManagementClient(
    credential=credential,
    subscription_id="your-subscription-id"
)

Azure Developer CLI Setup:

# Install Azure Developer CLI
curl -fsSL https://aka.ms/install-azd.sh | bash

# Sign in to Azure
azd auth login

# Initialize application
azd init

# Deploy application
azd up

AzurePowerShellCredential

Authenticates by requesting tokens from Azure PowerShell. Uses the account currently signed in via Connect-AzAccount cmdlet, enabling authentication for PowerShell-based workflows and scripts.

class AzurePowerShellCredential:
    def __init__(
        self,
        *,
        process_timeout: int = 10,
        **kwargs
    ):
        """
        Create an AzurePowerShellCredential that uses Azure PowerShell for authentication.
        
        Args:
            process_timeout: Seconds to wait for the Azure PowerShell process to complete (default: 10)
            
        Requirements:
            - Azure PowerShell module (Az) must be installed
            - PowerShell must be available in PATH (powershell.exe on Windows, pwsh on others)
            - User must be signed in via 'Connect-AzAccount'
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token from Azure PowerShell.
        
        Args:
            *scopes: Desired scopes for the access token
            claims: Additional claims required in the token (not supported by Azure PowerShell)
            tenant_id: Optional tenant ID override
            
        Returns:
            AccessToken: The access token with expiration information
            
        Raises:
            CredentialUnavailableError: Azure PowerShell not installed, not logged in, or process failed
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information from Azure PowerShell.
        
        Args:
            *scopes: Desired scopes for the access token
            options: Additional options for token acquisition
            
        Returns:
            dict: Token information including access token and metadata
        """

Usage Example:

from azure.identity import AzurePowerShellCredential

# Use Azure PowerShell authentication
credential = AzurePowerShellCredential()

# Use with Azure management operations
from azure.mgmt.compute import ComputeManagementClient

compute_client = ComputeManagementClient(
    credential=credential,
    subscription_id="your-subscription-id"
)

# List virtual machines using PowerShell authentication
for vm in compute_client.virtual_machines.list_all():
    print(f"VM: {vm.name}")

# Custom timeout for PowerShell operations
ps_credential = AzurePowerShellCredential(process_timeout=20)

Azure PowerShell Setup:

# Install Azure PowerShell module
Install-Module -Name Az -AllowClobber -Force

# Sign in to Azure
Connect-AzAccount

# Sign in with specific tenant
Connect-AzAccount -Tenant "your-tenant-id"

# Set default subscription context
Set-AzContext -SubscriptionId "your-subscription-id"

# Verify current context
Get-AzContext

VisualStudioCodeCredential

Authenticates using Azure account information stored by the Azure Account extension in Visual Studio Code. Enables seamless authentication for VS Code-based development workflows.

class VisualStudioCodeCredential:
    def __init__(
        self,
        *,
        authority: Optional[str] = None,
        tenant_id: Optional[str] = None,
        **kwargs
    ):
        """
        Create a VisualStudioCodeCredential that uses VS Code Azure Account extension.
        
        Args:
            authority: Authority of a Microsoft Entra endpoint
            tenant_id: Microsoft Entra tenant ID to restrict authentication scope
            
        Requirements:
            - Visual Studio Code must be installed
            - Azure Account extension must be installed and signed in
            - Authentication data must be accessible in VS Code settings
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token from Visual Studio Code Azure Account extension.
        
        Args:
            *scopes: Desired scopes for the access token
            claims: Additional claims required in the token (not supported by VS Code)
            tenant_id: Optional tenant ID override
            
        Returns:
            AccessToken: The access token with expiration information
            
        Raises:
            CredentialUnavailableError: VS Code not installed, Azure Account extension not available, or not signed in
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information from VS Code.
        
        Args:
            *scopes: Desired scopes for the access token
            options: Additional options for token acquisition
            
        Returns:
            dict: Token information including access token and metadata
        """

Usage Example:

from azure.identity import VisualStudioCodeCredential

# Use VS Code Azure Account extension authentication
credential = VisualStudioCodeCredential()

# Use in VS Code integrated development
from azure.keyvault.secrets import SecretClient

secret_client = SecretClient(
    vault_url="https://vault.vault.azure.net/",
    credential=credential
)

# Access secrets during development
try:
    secret = secret_client.get_secret("api-key")
    print("Retrieved secret successfully")
except Exception as e:
    print(f"Failed to retrieve secret: {e}")

# Tenant-specific authentication in VS Code
tenant_credential = VisualStudioCodeCredential(
    tenant_id="your-tenant-id"
)

Visual Studio Code Setup:

  1. Install Visual Studio Code
  2. Install Azure Account extension from VS Code marketplace
  3. Open VS Code and sign in to Azure Account extension
  4. Use Ctrl+Shift+P → "Azure: Sign In" to authenticate

SharedTokenCacheCredential

Authenticates using tokens cached by Microsoft developer tools including Visual Studio, Azure CLI, and other Microsoft applications. Provides access to shared token cache for seamless cross-tool authentication.

class SharedTokenCacheCredential:
    def __init__(
        self,
        username: Optional[str] = None,
        *,
        authority: Optional[str] = None,
        tenant_id: Optional[str] = None,
        cache_persistence_options: Optional[TokenCachePersistenceOptions] = None,
        **kwargs
    ):
        """
        Create a SharedTokenCacheCredential that uses shared token cache from Microsoft tools.
        
        Args:
            username: Username (typically email address) to filter cached accounts
            authority: Authority of a Microsoft Entra endpoint
            tenant_id: Microsoft Entra tenant ID to restrict authentication scope
            cache_persistence_options: Configuration for persistent token caching
            
        Note:
            This credential accesses tokens cached by Microsoft applications like Visual Studio,
            Azure CLI, and other tools that use MSAL (Microsoft Authentication Library).
        """

    @staticmethod
    def supported() -> bool:
        """
        Determine whether the shared token cache is supported on this platform.
        
        Returns:
            bool: True if shared token cache is supported, False otherwise
            
        Note:
            Shared token cache is primarily supported on Windows and macOS.
            Linux support varies by distribution and installed tools.
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token from the shared token cache.
        
        Args:
            *scopes: Desired scopes for the access token
            claims: Additional claims required in the token
            tenant_id: Optional tenant ID override
            
        Returns:
            AccessToken: The access token with expiration information
            
        Raises:
            CredentialUnavailableError: No valid tokens in shared cache or cache not supported
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information from shared cache.
        
        Args:
            *scopes: Desired scopes for the access token
            options: Additional options for token acquisition
            
        Returns:
            dict: Token information including access token and metadata
        """

Usage Example:

from azure.identity import SharedTokenCacheCredential

# Check if shared token cache is supported
if SharedTokenCacheCredential.supported():
    # Use shared token cache for seamless authentication
    credential = SharedTokenCacheCredential()
    
    # Filter by specific username if multiple accounts cached
    user_credential = SharedTokenCacheCredential(
        username="user@example.com"
    )
    
    # Use with Azure SDK
    from azure.storage.blob import BlobServiceClient
    
    blob_client = BlobServiceClient(
        account_url="https://account.blob.core.windows.net", 
        credential=credential
    )
else:
    print("Shared token cache not supported on this platform")
    # Fall back to other authentication method

Developer Credential Integration Patterns

DefaultAzureCredential with Developer Tools

from azure.identity import DefaultAzureCredential

# DefaultAzureCredential automatically includes developer credentials
# in this order (after environment and managed identity):
# 1. SharedTokenCacheCredential  
# 2. VisualStudioCodeCredential (excluded by default)
# 3. AzureCliCredential
# 4. AzurePowerShellCredential  
# 5. AzureDeveloperCliCredential

credential = DefaultAzureCredential()

# Customize which developer credentials are included
dev_credential = DefaultAzureCredential(
    exclude_cli_credential=False,           # Include Azure CLI
    exclude_powershell_credential=False,    # Include Azure PowerShell
    exclude_developer_cli_credential=False, # Include Azure Developer CLI
    exclude_visual_studio_code_credential=False,  # Include VS Code
    exclude_shared_token_cache_credential=False   # Include shared cache
)

# Development-only configuration
local_dev_credential = DefaultAzureCredential(
    exclude_managed_identity_credential=True,    # Skip managed identity locally
    exclude_environment_credential=True,         # Skip environment variables
    exclude_workload_identity_credential=True    # Skip workload identity
)

Custom Developer Credential Chain

from azure.identity import ChainedTokenCredential, AzureCliCredential, AzurePowerShellCredential

# Create custom developer credential chain
dev_chain = ChainedTokenCredential(
    AzureCliCredential(),           # Try Azure CLI first
    AzurePowerShellCredential(),    # Fall back to PowerShell
    VisualStudioCodeCredential()    # Fall back to VS Code
)

# Use in development environment
from azure.keyvault.secrets import SecretClient

secret_client = SecretClient(
    vault_url="https://vault.vault.azure.net/",
    credential=dev_chain
)

Environment Detection and Fallback

import os
from azure.identity import (
    DefaultAzureCredential, 
    AzureCliCredential,
    CredentialUnavailableError
)

def get_development_credential():
    """Get appropriate credential for current development environment."""
    
    # Check if running in Azure (production)
    if os.environ.get("WEBSITE_SITE_NAME") or os.environ.get("FUNCTIONS_WORKER_RUNTIME"):
        # Use DefaultAzureCredential for managed identity in Azure
        return DefaultAzureCredential()
    
    # Local development - try developer tools
    try:
        # Test Azure CLI first (most common)
        cli_credential = AzureCliCredential()
        cli_credential.get_token("https://management.azure.com/.default")
        return cli_credential
    except CredentialUnavailableError:
        pass
    
    # Fall back to full DefaultAzureCredential chain
    return DefaultAzureCredential(
        exclude_managed_identity_credential=True  # Skip in local dev
    )

# Use in application
credential = get_development_credential()

Troubleshooting Developer Credentials

Common Issues and Solutions

from azure.identity import AzureCliCredential, CredentialUnavailableError
import subprocess
import logging

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)

def diagnose_azure_cli():
    """Diagnose Azure CLI authentication issues."""
    try:
        # Check if Azure CLI is installed
        result = subprocess.run(["az", "--version"], capture_output=True, text=True)
        print(f"Azure CLI version: {result.stdout}")
        
        # Check current account
        result = subprocess.run(["az", "account", "show"], capture_output=True, text=True)
        if result.returncode == 0:
            print("Azure CLI is logged in")
            print(result.stdout)
        else:
            print("Azure CLI not logged in. Run 'az login'")
            
    except FileNotFoundError:
        print("Azure CLI not installed")
    except Exception as e:
        print(f"Error checking Azure CLI: {e}")

def test_credential_chain():
    """Test different developer credentials."""
    from azure.identity import (
        AzureCliCredential,
        AzurePowerShellCredential, 
        VisualStudioCodeCredential,
        SharedTokenCacheCredential
    )
    
    credentials = [
        ("Azure CLI", AzureCliCredential()),
        ("Azure PowerShell", AzurePowerShellCredential()),
        ("VS Code", VisualStudioCodeCredential()),
        ("Shared Cache", SharedTokenCacheCredential())
    ]
    
    for name, credential in credentials:
        try:
            token = credential.get_token("https://management.azure.com/.default")
            print(f"✓ {name}: Successfully acquired token")
        except CredentialUnavailableError as e:
            print(f"✗ {name}: {e}")
        except Exception as e:
            print(f"✗ {name}: Unexpected error - {e}")

# Run diagnostics
diagnose_azure_cli()
test_credential_chain()

Process Timeout Configuration

from azure.identity import AzureCliCredential, AzurePowerShellCredential

# Increase timeout for slow systems or networks
slow_cli = AzureCliCredential(process_timeout=30)
slow_ps = AzurePowerShellCredential(process_timeout=30)

# Decrease timeout for responsive systems
fast_cli = AzureCliCredential(process_timeout=5)

Cross-Platform Considerations

import platform
from azure.identity import DefaultAzureCredential

def get_platform_appropriate_credential():
    """Get credential appropriate for current platform."""
    system = platform.system()
    
    if system == "Windows":
        # Windows supports all developer credentials
        return DefaultAzureCredential(
            exclude_visual_studio_code_credential=False
        )
    elif system == "Darwin":  # macOS
        # macOS supports most developer credentials
        return DefaultAzureCredential(
            exclude_powershell_credential=False  # PowerShell Core available on macOS
        )
    else:  # Linux and others
        # Linux primarily supports Azure CLI and PowerShell Core
        return DefaultAzureCredential(
            exclude_visual_studio_code_credential=True,  # Limited support
            exclude_shared_token_cache_credential=True   # Limited support
        )

credential = get_platform_appropriate_credential()

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