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

azure-platform.mddocs/

Azure Platform Credentials

Leverage Azure's native authentication mechanisms for secure, credential-free authentication within Azure environments. These credentials provide automatic authentication for Azure-hosted applications without requiring stored secrets or user interaction.

Capabilities

ManagedIdentityCredential

Authenticates using Azure Managed Identity, providing automatic authentication for Azure services including Virtual Machines, App Service, Function Apps, Azure Container Instances, and Azure Kubernetes Service. Eliminates the need to store credentials in application code.

class ManagedIdentityCredential:
    def __init__(
        self,
        *,
        client_id: Optional[str] = None,
        identity_config: Optional[Mapping[str, str]] = None,
        **kwargs
    ):
        """
        Create a ManagedIdentityCredential for Azure managed identity authentication.
        
        Args:
            client_id: User-assigned managed identity's client ID. If not specified, uses system-assigned identity.
            identity_config: Configuration for user-assigned identity. Use either:
                - {"client_id": "client-id-value"} for user-assigned identity by client ID
                - {"object_id": "object-id-value"} for user-assigned identity by object ID  
                - {"mi_res_id": "resource-id-value"} for user-assigned identity by Azure resource ID
                
        Note:
            - System-assigned identity: Available automatically on supported Azure services
            - User-assigned identity: Must be created and assigned to the Azure resource
            - Only specify client_id OR identity_config, not both
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token using managed identity.
        
        Args:
            *scopes: Desired scopes for the access token
            claims: Additional claims required in the token (not supported for managed identity)
            tenant_id: Optional tenant ID override (not supported for managed identity)
            
        Returns:
            AccessToken: The access token with expiration information
            
        Raises:
            CredentialUnavailableError: Managed identity is not available on this platform
            ClientAuthenticationError: Failed to authenticate with managed identity service
        """

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

Usage Examples:

from azure.identity import ManagedIdentityCredential

# System-assigned managed identity (default)
credential = ManagedIdentityCredential()

# User-assigned managed identity by client ID
user_assigned_credential = ManagedIdentityCredential(
    client_id="your-user-assigned-identity-client-id"
)

# User-assigned managed identity by object ID
object_id_credential = ManagedIdentityCredential(
    identity_config={"object_id": "your-identity-object-id"}
)

# User-assigned managed identity by Azure resource ID
resource_id_credential = ManagedIdentityCredential(
    identity_config={"mi_res_id": "/subscriptions/{sub}/resourcegroups/{rg}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{name}"}
)

# Use with Azure SDK
from azure.storage.blob import BlobServiceClient

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

# Virtual Machine authentication example
from azure.keyvault.secrets import SecretClient

# This automatically works on Azure VMs with managed identity enabled
secret_client = SecretClient(
    vault_url="https://vault.vault.azure.net/",
    credential=ManagedIdentityCredential()
)

secret = secret_client.get_secret("database-connection-string")

WorkloadIdentityCredential

Authenticates using Azure workload identity for Kubernetes workloads. Enables pods running in Azure Kubernetes Service (AKS) to authenticate using Kubernetes service account tokens federated with Azure Active Directory.

class WorkloadIdentityCredential:
    def __init__(
        self,
        *,
        tenant_id: Optional[str] = None,
        client_id: Optional[str] = None,
        token_file_path: Optional[str] = None,
        authority: Optional[str] = None,
        **kwargs
    ):
        """
        Create a WorkloadIdentityCredential for Kubernetes workload identity authentication.
        
        Args:
            tenant_id: ID of the application's Microsoft Entra tenant (defaults to AZURE_TENANT_ID env var)
            client_id: The application's client ID (defaults to AZURE_CLIENT_ID env var)  
            token_file_path: Path to JWT token file (defaults to AZURE_FEDERATED_TOKEN_FILE env var)
            authority: Authority of a Microsoft Entra endpoint
            
        Environment Variables:
            AZURE_TENANT_ID: Microsoft Entra tenant ID
            AZURE_CLIENT_ID: Azure AD application client ID
            AZURE_FEDERATED_TOKEN_FILE: Path to Kubernetes service account token file
            
        Note:
            Typically used in Azure Kubernetes Service (AKS) pods with workload identity enabled.
            The token file is automatically mounted by the workload identity webhook.
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token using workload identity.
        
        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: Required environment variables or token file not available
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information.
        
        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 WorkloadIdentityCredential

# Workload identity (automatically configured in AKS pods)
credential = WorkloadIdentityCredential()

# Explicit configuration
explicit_credential = WorkloadIdentityCredential(
    tenant_id="your-tenant-id",
    client_id="your-client-id",
    token_file_path="/var/run/secrets/azure/tokens/azure-identity-token"
)

# Use in Kubernetes pod
from azure.keyvault.secrets import SecretClient

# This works automatically in AKS pods with workload identity
secret_client = SecretClient(
    vault_url="https://vault.vault.azure.net/",
    credential=WorkloadIdentityCredential()
)

AzurePipelinesCredential

Authenticates using Azure Pipelines service connections for secure authentication within Azure DevOps pipelines without exposing credentials in pipeline definitions.

class AzurePipelinesCredential:
    def __init__(
        self,
        *,
        system_access_token: str,
        service_connection_id: str,
        tenant_id: Optional[str] = None,
        **kwargs
    ):
        """
        Create an AzurePipelinesCredential for Azure Pipelines authentication.
        
        Args:
            system_access_token: The System.AccessToken value from Azure Pipelines
            service_connection_id: The service connection ID for the Azure Resource Manager connection
            tenant_id: ID of the application's Microsoft Entra tenant (optional)
            
        Note:
            This credential exchanges the Azure Pipelines system access token for an Azure AD token
            using the specified service connection. The service connection must be configured in
            Azure DevOps with appropriate permissions.
        """

    def get_token(self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs) -> AccessToken:
        """
        Request an access token using Azure Pipelines service connection.
        
        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: Not running in Azure Pipelines or invalid service connection
        """

    def get_token_info(self, *scopes: str, options: Optional[dict] = None) -> dict:
        """
        Request access token with additional information.
        
        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:

# In Azure Pipelines YAML
# - task: PythonScript@0
#   env:
#     SYSTEM_ACCESSTOKEN: $(System.AccessToken)

import os
from azure.identity import AzurePipelinesCredential

# Use in Azure Pipelines
credential = AzurePipelinesCredential(
    system_access_token=os.environ["SYSTEM_ACCESSTOKEN"],
    service_connection_id="your-service-connection-id"
)

# Deploy to Azure from pipeline
from azure.mgmt.resource import ResourceManagementClient

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

Platform-Specific Credentials

The following credentials are used internally by Azure services and typically not used directly in application code:

Service Fabric Credential

# Internal use - Service Fabric Mesh applications
class ServiceFabricCredential:
    """Authenticates using Service Fabric managed identity (internal use)."""

App Service Credential

# Internal use - Azure App Service applications
class AppServiceCredential:
    """Authenticates using App Service managed identity (internal use)."""

Azure Arc Credential

# Internal use - Azure Arc enabled servers
class AzureArcCredential:
    """Authenticates using Azure Arc managed identity (internal use)."""

Azure ML Credential

# Internal use - Azure Machine Learning compute
class AzureMLCredential:
    """Authenticates using Azure ML managed identity (internal use)."""

Cloud Shell Credential

# Internal use - Azure Cloud Shell
class CloudShellCredential:
    """Authenticates using Azure Cloud Shell managed identity (internal use)."""

IMDS Credential

# Internal use - Azure Instance Metadata Service
class ImdsCredential:
    """Authenticates using Azure IMDS managed identity endpoint (internal use)."""

Azure Environment Support

Supported Azure Services

Virtual Machines:

  • System-assigned managed identity: Enabled in VM settings
  • User-assigned managed identity: Assigned to VM

App Service & Function Apps:

  • System-assigned managed identity: Enabled in Identity settings
  • User-assigned managed identity: Assigned in Identity settings

Azure Container Instances:

  • User-assigned managed identity: Specified during container creation

Azure Kubernetes Service:

  • Workload identity: Pods with federated service accounts
  • Managed identity: Node pools with managed identity

Azure Container Apps:

  • System-assigned managed identity: Enabled in Identity settings
  • User-assigned managed identity: Assigned in Identity settings

Azure Logic Apps:

  • System-assigned managed identity: Enabled automatically
  • User-assigned managed identity: Assigned in Identity settings

Azure Cloud Support

# Public cloud (default)
credential = ManagedIdentityCredential()

# Azure Government
gov_credential = WorkloadIdentityCredential(
    authority="https://login.microsoftonline.us"
)

# Azure China  
china_credential = WorkloadIdentityCredential(
    authority="https://login.chinacloudapi.cn"
)

Best Practices

Managed Identity Recommendations

  1. Prefer system-assigned identity for single-service scenarios
  2. Use user-assigned identity for multi-service or complex scenarios
  3. Grant minimum required permissions using Azure RBAC
  4. Monitor identity usage with Azure Monitor and Activity Log
  5. Test authentication in both development and production environments

Workload Identity Setup

# Enable workload identity on AKS cluster
az aks update \
    --resource-group myResourceGroup \
    --name myAKSCluster \
    --enable-workload-identity

# Create user-assigned managed identity
az identity create \
    --resource-group myResourceGroup \
    --name myUserAssignedIdentity

# Create Kubernetes service account with federation
az aks get-credentials --resource-group myResourceGroup --name myAKSCluster

kubectl create serviceaccount workload-identity-sa

# Establish federated credential
az identity federated-credential create \
    --name myFederatedIdentity \
    --identity-name myUserAssignedIdentity \
    --resource-group myResourceGroup \
    --issuer $(az aks show --resource-group myResourceGroup --name myAKSCluster --query "oidcIssuerProfile.issuerUrl" -o tsv) \
    --subject system:serviceaccount:default:workload-identity-sa

Pod Configuration for Workload Identity

# Kubernetes deployment with workload identity
apiVersion: apps/v1
kind: Deployment
metadata:
  name: workload-identity-app
spec:
  template:
    metadata:
      labels:
        azure.workload.identity/use: "true"
    spec:
      serviceAccountName: workload-identity-sa
      containers:
      - name: app
        image: myapp:latest
        env:
        - name: AZURE_CLIENT_ID
          value: "your-client-id"
        - name: AZURE_TENANT_ID  
          value: "your-tenant-id"

Error Handling and Diagnostics

from azure.identity import ManagedIdentityCredential, CredentialUnavailableError
from azure.core.exceptions import ClientAuthenticationError
import logging

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

try:
    credential = ManagedIdentityCredential()
    token = credential.get_token("https://management.azure.com/.default")
    print("Managed identity authentication successful")
    
except CredentialUnavailableError as e:
    print(f"Managed identity not available: {e}")
    # Fallback to other authentication method
    
except ClientAuthenticationError as e:
    print(f"Authentication failed: {e}")
    # Check managed identity configuration and permissions

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