CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-core

Microsoft Azure Core Library providing foundational infrastructure for Azure SDK Python clients

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

authentication-and-credentials.mddocs/

Authentication and Credentials

Azure Core provides comprehensive authentication mechanisms supporting OAuth tokens, API keys, and Shared Access Signature (SAS) credentials. The authentication system is designed to work seamlessly with both synchronous and asynchronous Azure SDK clients.

Capabilities

Token-Based Authentication

OAuth token authentication using the TokenCredential protocol for Azure Active Directory and managed identity authentication.

from azure.core.credentials import TokenCredential, AccessToken, AccessTokenInfo, TokenRequestOptions
from typing import Protocol, Union

class TokenCredential(Protocol):
    """Protocol for OAuth token credential providers."""
    def get_token(self, *scopes: str, **kwargs) -> AccessToken: ...

class SupportsTokenInfo(Protocol):
    """Protocol for extended token providers with additional token information."""
    def get_token_info(self, *scopes: str, **kwargs) -> AccessTokenInfo: ...

TokenProvider = Union[TokenCredential, SupportsTokenInfo]

Token Types

from typing import NamedTuple

class AccessToken(NamedTuple):
    """OAuth access token container."""
    token: str
    expires_on: int  # Unix timestamp

class AccessTokenInfo:
    """Extended access token with additional properties."""
    def __init__(self, token: str, expires_on: int, **kwargs): ...
    
    @property
    def token(self) -> str: ...
    
    @property 
    def expires_on(self) -> int: ...

class TokenRequestOptions(TypedDict, total=False):
    """Options for token requests."""
    claims: str
    tenant_id: str
    enable_cae: bool

API Key Authentication

Simple API key-based authentication for services that use API keys instead of OAuth tokens.

class AzureKeyCredential:
    """API key-based credential."""
    def __init__(self, key: str): ...
    
    def update(self, key: str) -> None:
        """Update the API key."""
        ...
    
    @property
    def key(self) -> str: ...

Named Key Credentials

Authentication using name/key pairs for scenarios requiring both an identifier and secret.

from typing import NamedTuple

class AzureNamedKey(NamedTuple):
    """Name and key pair container."""
    name: str
    key: str

class AzureNamedKeyCredential:
    """Named key pair credential."""
    def __init__(self, name: str, key: str): ...
    
    def update(self, name: str, key: str) -> None:
        """Update the name and key."""
        ...
    
    @property
    def named_key(self) -> AzureNamedKey: ...

SAS Credentials

Shared Access Signature authentication for Azure Storage and other services supporting SAS tokens.

class AzureSasCredential:
    """Shared Access Signature credential."""
    def __init__(self, signature: str): ...
    
    def update(self, signature: str) -> None:
        """Update the SAS token."""
        ...
    
    @property
    def signature(self) -> str: ...

Async Token Authentication

Asynchronous versions of token credential protocols for async Azure SDK clients.

from azure.core.credentials_async import AsyncTokenCredential, AsyncSupportsTokenInfo

class AsyncTokenCredential(Protocol):
    """Async protocol for OAuth token credential providers."""
    async def get_token(self, *scopes: str, **kwargs) -> AccessToken: ...

class AsyncSupportsTokenInfo(Protocol):
    """Async protocol for extended token providers."""
    async def get_token_info(self, *scopes: str, **kwargs) -> AccessTokenInfo: ...

Usage Examples

Basic Token Authentication

from azure.core.credentials import TokenCredential
from azure.core import PipelineClient
from azure.core.pipeline.policies import BearerTokenCredentialPolicy

# Assume you have a token credential from azure-identity
# from azure.identity import DefaultAzureCredential
# credential = DefaultAzureCredential()

# Create pipeline with token authentication
policies = [BearerTokenCredentialPolicy(credential, "https://management.azure.com/.default")]
client = PipelineClient(base_url="https://management.azure.com", policies=policies)

API Key Authentication

from azure.core.credentials import AzureKeyCredential
from azure.core.pipeline.policies import AzureKeyCredentialPolicy

# Create API key credential
credential = AzureKeyCredential("your-api-key")

# Use in pipeline policy
policy = AzureKeyCredentialPolicy(credential, "X-API-Key")

# Update key when needed
credential.update("new-api-key")

SAS Authentication

from azure.core.credentials import AzureSasCredential
from azure.core.pipeline.policies import AzureSasCredentialPolicy

# Create SAS credential
sas_token = "?sv=2020-04-08&sr=c&si=policy&sig=signature"
credential = AzureSasCredential(sas_token)

# Use in pipeline policy
policy = AzureSasCredentialPolicy(credential)

# Update SAS token when needed
credential.update("new-sas-token")

Async Token Authentication

import asyncio
from azure.core.credentials_async import AsyncTokenCredential
from azure.core import AsyncPipelineClient

async def authenticate_async():
    # Assume you have an async token credential
    # from azure.identity.aio import DefaultAzureCredential
    # credential = DefaultAzureCredential()
    
    # Use with async pipeline client
    client = AsyncPipelineClient(base_url="https://api.example.com")
    
    # Get token asynchronously
    token = await credential.get_token("https://api.example.com/.default")
    print(f"Token expires at: {token.expires_on}")

# asyncio.run(authenticate_async())

Custom Token Request Options

from azure.core.credentials import TokenRequestOptions

# Request token with specific options
token_options: TokenRequestOptions = {
    "claims": '{"access_token": {"xms_cc": {"values": ["cp1"]}}}',
    "tenant_id": "specific-tenant-id",
    "enable_cae": True
}

# Most credential implementations support passing these options
# token = credential.get_token("scope", **token_options)

Authentication Pipeline Policies

Azure Core provides pipeline policies that automatically handle authentication for different credential types.

Bearer Token Policy

from azure.core.pipeline.policies import BearerTokenCredentialPolicy, AsyncBearerTokenCredentialPolicy

class BearerTokenCredentialPolicy(HTTPPolicy):
    """Policy for Bearer token authentication."""
    def __init__(self, credential: TokenCredential, *scopes: str, **kwargs): ...

class AsyncBearerTokenCredentialPolicy(AsyncHTTPPolicy):
    """Async policy for Bearer token authentication.""" 
    def __init__(self, credential: AsyncTokenCredential, *scopes: str, **kwargs): ...

API Key Policy

from azure.core.pipeline.policies import AzureKeyCredentialPolicy

class AzureKeyCredentialPolicy(HTTPPolicy):
    """Policy for API key authentication."""
    def __init__(self, credential: AzureKeyCredential, name: str, **kwargs): ...

SAS Policy

from azure.core.pipeline.policies import AzureSasCredentialPolicy

class AzureSasCredentialPolicy(HTTPPolicy):
    """Policy for SAS authentication."""
    def __init__(self, credential: AzureSasCredential, **kwargs): ...

Best Practices

Credential Management

  • Store credentials securely and never hard-code them in source code
  • Use Azure Key Vault or environment variables for credential storage
  • Rotate credentials regularly and update them using the update() methods
  • Use managed identities when running in Azure environments

Token Caching

  • Token credentials automatically handle token caching and renewal
  • Tokens are cached until near expiration to minimize authentication requests
  • Multiple clients can share the same credential instance for efficiency

Error Handling

  • Handle ClientAuthenticationError for authentication failures
  • Implement retry logic for transient authentication errors
  • Monitor token expiration and handle renewal failures gracefully

Async Considerations

  • Use async credential types with async pipeline clients
  • Properly handle async context management for credential cleanup
  • Be aware of token refresh timing in long-running async operations

Install with Tessl CLI

npx tessl i tessl/pypi-azure-core

docs

async-programming-patterns.md

authentication-and-credentials.md

configuration-and-settings.md

distributed-tracing-and-diagnostics.md

error-handling-and-exceptions.md

http-pipeline-and-policies.md

index.md

paging-and-result-iteration.md

polling-and-long-running-operations.md

rest-api-abstraction.md

transport-and-networking.md

utilities-and-helpers.md

tile.json