CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-adal

Azure Active Directory Authentication Library for Python that provides OAuth2/OpenID Connect authentication flows and token management for accessing Azure AD protected resources

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

authentication-flows.mddocs/

Authentication Flows

Core authentication functionality supporting all major OAuth2 flows for Azure Active Directory integration. Each flow is designed for specific use cases and security requirements.

Capabilities

AuthenticationContext Constructor

Creates a new authentication context for interacting with Azure Active Directory. The context manages authority validation, token caching, and HTTP client configuration.

def __init__(self, authority, validate_authority=None, cache=None, 
             api_version=None, timeout=None, enable_pii=False, 
             verify_ssl=None, proxies=None):
    """
    Initialize authentication context.
    
    Parameters:
    - authority (str): Azure AD authority URL (e.g., 'https://login.microsoftonline.com/tenant-id')
    - validate_authority (bool, optional): Whether to validate authority URL (default: True)
    - cache (TokenCache, optional): Custom token cache instance
    - api_version (str, optional): Azure AD API version
    - timeout (int, optional): HTTP request timeout in seconds
    - enable_pii (bool, optional): Enable personally identifiable information in logs
    - verify_ssl (bool, optional): Verify SSL certificates (default: True)
    - proxies (dict, optional): HTTP proxy configuration
    """

Options Property

Gets or sets global configuration options for the authentication context. This property manages context-wide settings that affect all token acquisition operations.

@property
def options(self):
    """
    Get current context options.
    
    Returns:
    dict: Dictionary containing current context configuration
    """

@options.setter
def options(self, val):
    """
    Set context options.
    
    Parameters:
    - val (dict): Dictionary containing configuration options to set
    """

Cache-based Token Acquisition

Retrieves tokens from cache with automatic refresh when needed. This is the most efficient method when tokens are already cached.

def acquire_token(self, resource, user_id, client_id):
    """
    Get token from cache with refresh if needed.
    
    Parameters:
    - resource (str): URI identifying the target resource
    - user_id (str): Username or user identifier
    - client_id (str): OAuth2 client ID of the application
    
    Returns:
    dict: Authentication result with access token, refresh token, and metadata
    """

Usage Example:

import adal

context = adal.AuthenticationContext('https://login.microsoftonline.com/tenant-id')
token = context.acquire_token(
    resource='https://management.azure.com/',
    user_id='user@tenant.com',
    client_id='your-client-id'
)

Username/Password Flow

Authenticates using user credentials directly. This flow requires users to provide their username and password to the application.

def acquire_token_with_username_password(self, resource, username, password, client_id):
    """
    Authenticate using username and password.
    
    Parameters:
    - resource (str): URI identifying the target resource
    - username (str): User's username or email address
    - password (str): User's password
    - client_id (str): OAuth2 client ID of the application
    
    Returns:
    dict: Authentication result with access token, refresh token, and metadata
    """

Usage Example:

token = context.acquire_token_with_username_password(
    resource='https://graph.microsoft.com/',
    username='user@tenant.com',
    password='user-password',
    client_id='your-client-id'
)

Client Credentials Flow

Server-to-server authentication using application credentials. This flow is used for daemon applications and background services.

def acquire_token_with_client_credentials(self, resource, client_id, client_secret):
    """
    Authenticate using client credentials (application identity).
    
    Parameters:
    - resource (str): URI identifying the target resource
    - client_id (str): OAuth2 client ID of the application
    - client_secret (str): Client secret for the application
    
    Returns:
    dict: Authentication result with access token and metadata
    """

Usage Example:

token = context.acquire_token_with_client_credentials(
    resource='https://management.azure.com/',
    client_id='your-client-id',
    client_secret='your-client-secret'
)

Authorization Code Flow

Web application authentication flow where users are redirected to Azure AD for authentication and authorization code is exchanged for tokens.

def acquire_token_with_authorization_code(self, authorization_code, redirect_uri, 
                                         resource, client_id, client_secret=None, 
                                         code_verifier=None):
    """
    Exchange authorization code for access token.
    
    Parameters:
    - authorization_code (str): Authorization code received from Azure AD
    - redirect_uri (str): Redirect URI used in authorization request
    - resource (str): URI identifying the target resource
    - client_id (str): OAuth2 client ID of the application
    - client_secret (str, optional): Client secret (required for confidential clients)
    - code_verifier (str, optional): PKCE code verifier for public clients
    
    Returns:
    dict: Authentication result with access token, refresh token, and metadata
    """

Usage Example:

# After receiving authorization code from redirect
token = context.acquire_token_with_authorization_code(
    authorization_code='received-auth-code',
    redirect_uri='https://your-app.com/callback',
    resource='https://graph.microsoft.com/',
    client_id='your-client-id',
    client_secret='your-client-secret'
)

Refresh Token Flow

Refreshes expired access tokens using a refresh token without requiring user interaction.

def acquire_token_with_refresh_token(self, refresh_token, client_id, resource, 
                                    client_secret=None):
    """
    Use refresh token to get new access token.
    
    Parameters:
    - refresh_token (str): Valid refresh token
    - client_id (str): OAuth2 client ID of the application
    - resource (str): URI identifying the target resource
    - client_secret (str, optional): Client secret (required for confidential clients)
    
    Returns:
    dict: Authentication result with new access token, refresh token, and metadata
    """

Usage Example:

token = context.acquire_token_with_refresh_token(
    refresh_token='stored-refresh-token',
    client_id='your-client-id',
    resource='https://management.azure.com/',
    client_secret='your-client-secret'
)

Certificate-based Authentication

High-security authentication using X.509 certificates instead of client secrets. Commonly used in enterprise environments.

def acquire_token_with_client_certificate(self, resource, client_id, certificate, 
                                         thumbprint, public_certificate=None):
    """
    Authenticate using client certificate.
    
    Parameters:
    - resource (str): URI identifying the target resource
    - client_id (str): OAuth2 client ID of the application
    - certificate (str): PEM-formatted private key certificate
    - thumbprint (str): SHA1 thumbprint of the certificate
    - public_certificate (str, optional): PEM-formatted public certificate
    
    Returns:
    dict: Authentication result with access token and metadata
    """

Usage Example:

# Load certificate from file
with open('cert.pem', 'r') as cert_file:
    certificate = cert_file.read()

token = context.acquire_token_with_client_certificate(
    resource='https://management.azure.com/',
    client_id='your-client-id',
    certificate=certificate,
    thumbprint='certificate-thumbprint'
)

Error Handling

All authentication methods may raise AdalError exceptions for various failure conditions:

  • Invalid credentials
  • Network connectivity issues
  • Authority validation failures
  • Token format errors
  • Expired refresh tokens
try:
    token = context.acquire_token_with_client_credentials(
        resource, client_id, client_secret
    )
except adal.AdalError as e:
    print(f"Authentication failed: {e}")
    if e.error_response:
        print(f"Error details: {e.error_response}")

Install with Tessl CLI

npx tessl i tessl/pypi-adal

docs

authentication-flows.md

device-code-flow.md

index.md

logging-error-handling.md

token-caching.md

tile.json