or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

common-auth-flows.mdconfidential-client.mdindex.mdmanaged-identity.mdpublic-client.mdsecurity-advanced.mdtoken-cache.md
tile.json

tessl/pypi-msal

Microsoft Authentication Library for Python enabling OAuth2/OIDC authentication with Microsoft identity platform

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/msal@1.33.x

To install, run

npx @tessl/cli install tessl/pypi-msal@1.33.0

index.mddocs/

MSAL - Microsoft Authentication Library

The Microsoft Authentication Library (MSAL) for Python enables your app to access the Microsoft Cloud by supporting authentication of users with Microsoft Azure Active Directory accounts (AAD), Microsoft Accounts (MSA), External identities, and Azure AD B2C accounts using industry standard OAuth2 and OpenID Connect protocols.

MSAL Python provides both public client applications for desktop/mobile scenarios and confidential client applications for server-side scenarios, with automatic token caching, refresh capabilities, broker support for enhanced security, and extensive configuration options for different authentication flows.

Package Information

  • Package Name: msal
  • Language: Python
  • Installation: pip install msal
  • Optional broker support: pip install msal[broker]

Core Imports

import msal

Common imports for different application types:

from msal import PublicClientApplication, ConfidentialClientApplication

Token caching imports:

from msal import TokenCache, SerializableTokenCache

Managed identity imports:

from msal import ManagedIdentityClient, SystemAssignedManagedIdentity, UserAssignedManagedIdentity

Version information:

import msal
print(msal.__version__)  # "1.33.0"

Basic Usage

Public Client Application (Desktop/Mobile)

import msal

# Create a public client application
app = msal.PublicClientApplication(
    client_id="your-client-id",
    authority="https://login.microsoftonline.com/your-tenant-id"
)

# Get accounts from cache
accounts = app.get_accounts()

# Try silent authentication first
result = None
if accounts:
    result = app.acquire_token_silent(
        scopes=["User.Read"],
        account=accounts[0]
    )

# If silent fails, use interactive authentication
if not result:
    result = app.acquire_token_interactive(
        scopes=["User.Read"]
    )

if "access_token" in result:
    print("Authentication successful!")
    print(f"Access token: {result['access_token'][:20]}...")
else:
    print(f"Authentication failed: {result.get('error_description')}")

Confidential Client Application (Server-side)

import msal

# Create a confidential client application
app = msal.ConfidentialClientApplication(
    client_id="your-client-id",
    client_credential="your-client-secret",
    authority="https://login.microsoftonline.com/your-tenant-id"
)

# Acquire token for client (Client Credentials flow)
result = app.acquire_token_for_client(
    scopes=["https://graph.microsoft.com/.default"]
)

if "access_token" in result:
    print("Authentication successful!")
    access_token = result["access_token"]
else:
    print(f"Authentication failed: {result.get('error_description')}")

Architecture

MSAL Python follows the OAuth2/OIDC protocol specifications with Microsoft identity platform extensions:

  • Application Types: PublicClientApplication for native apps, ConfidentialClientApplication for server apps
  • Token Management: Automatic caching, refresh, and persistence with TokenCache/SerializableTokenCache
  • Authentication Flows: Interactive, device flow, authorization code, username/password, client credentials, on-behalf-of
  • Security Features: Proof-of-Possession tokens, broker integration, certificate-based authentication
  • Azure Integration: Managed identity support, Azure AD B2C, multi-tenant applications

The library handles protocol complexities like token refresh, scope validation, and error handling while providing a simple, consistent API across different authentication scenarios.

Capabilities

Public Client Applications

Desktop and mobile application authentication with interactive browser flows, device code authentication for browserless devices, and optional broker integration for enhanced security through device identity.

class PublicClientApplication(ClientApplication):
    def __init__(
        self,
        client_id: str,
        client_credential=None,
        *,
        enable_broker_on_windows=None,
        enable_broker_on_mac=None,
        enable_broker_on_linux=None,
        enable_broker_on_wsl=None,
        **kwargs
    ): ...
    
    def acquire_token_interactive(
        self,
        scopes: list,
        prompt=None,
        login_hint=None,
        domain_hint=None,
        claims_challenge=None,
        timeout=None,
        port=None,
        extra_scopes_to_consent=None,
        max_age=None,
        parent_window_handle=None,
        on_before_launching_ui=None,
        auth_scheme=None,
        **kwargs
    ): ...
    
    def initiate_device_flow(self, scopes=None, **kwargs): ...
    
    def acquire_token_by_device_flow(self, flow, claims_challenge=None, **kwargs): ...

Public Client Applications

Confidential Client Applications

Server-side web application authentication with client credentials flow for service-to-service authentication, authorization code flow for web apps, and on-behalf-of flow for middle-tier services acting on behalf of users.

class ConfidentialClientApplication(ClientApplication):
    def __init__(
        self,
        client_id: str,
        client_credential,
        authority=None,
        **kwargs
    ): ...
    
    def acquire_token_for_client(
        self,
        scopes: list,
        claims_challenge=None,
        **kwargs
    ): ...
    
    def acquire_token_on_behalf_of(
        self,
        user_assertion: str,
        scopes: list,
        claims_challenge=None,
        **kwargs
    ): ...

Confidential Client Applications

Token Caching

Unified token cache system supporting both in-memory caching for single-session applications and persistent caching for multi-session scenarios. Includes automatic token refresh, account management, and cross-application token sharing.

class TokenCache:
    def __init__(self): ...
    
    def find(
        self,
        credential_type: str,
        target=None,
        query=None,
        now=None
    ) -> list: ...
    
    def add(self, event: dict, now=None): ...

class SerializableTokenCache(TokenCache):
    def serialize(self) -> str: ...
    
    def deserialize(self, state: str): ...

Token Caching

Common Authentication Flows

Shared authentication functionality including silent token acquisition from cache, authorization code flow initiation and completion, username/password authentication, refresh token handling, and account management across all application types.

class ClientApplication:
    def acquire_token_silent(
        self,
        scopes: list,
        account,
        authority=None,
        force_refresh=False,
        claims_challenge=None,
        **kwargs
    ): ...
    
    def initiate_auth_code_flow(
        self,
        scopes: list,
        redirect_uri=None,
        state=None,
        prompt=None,
        login_hint=None,
        **kwargs
    ): ...
    
    def acquire_token_by_auth_code_flow(
        self,
        auth_code_flow: dict,
        auth_response: dict,
        scopes=None,
        **kwargs
    ): ...
    
    def acquire_token_by_username_password(
        self,
        username: str,
        password: str,
        scopes: list,
        claims_challenge=None,
        auth_scheme=None,
        **kwargs
    ): ...
    
    def acquire_token_by_refresh_token(
        self,
        refresh_token: str,
        scopes: list,
        **kwargs
    ): ...
    
    def get_accounts(self, username=None) -> list: ...
    
    def remove_account(self, account): ...

Common Authentication Flows

Azure Managed Identity

Azure managed identity authentication for virtual machines, container instances, and other Azure services. Supports both system-assigned identities (automatically created with the resource) and user-assigned identities (standalone resources assigned to multiple services).

class ManagedIdentityClient:
    def __init__(
        self,
        managed_identity,
        http_client=None,
        token_cache=None,
        **kwargs
    ): ...
    
    def acquire_token_for_client(
        self,
        resource: str,
        claims_challenge=None
    ): ...

class SystemAssignedManagedIdentity:
    def __init__(self): ...

class UserAssignedManagedIdentity:
    def __init__(
        self,
        client_id=None,
        object_id=None,
        resource_id=None
    ): ...

Azure Managed Identity

Security and Advanced Features

Advanced security features including Proof-of-Possession (PoP) token authentication for enhanced security, certificate-based authentication with X.509 certificates, custom authentication schemes, and comprehensive error handling with detailed error information.

class PopAuthScheme:
    def __init__(
        self,
        http_method: str = None,
        url: str = None,
        nonce: str = None
    ): ...

def extract_certs(public_cert_content: str) -> list: ...

class Prompt:
    NONE = "none"
    LOGIN = "login"
    CONSENT = "consent"
    SELECT_ACCOUNT = "select_account"
    CREATE = "create"

Security and Advanced Features

Types

# Authentication result dictionary
AuthResult = dict  # Contains 'access_token', 'token_type', 'expires_in', etc.

# Account dictionary from cache
Account = dict  # Contains 'home_account_id', 'environment', 'username', etc.

# Auth code flow state dictionary
AuthCodeFlow = dict  # Contains 'auth_uri', 'state', 'code_verifier', etc.

# Device flow state dictionary  
DeviceFlow = dict  # Contains 'device_code', 'user_code', 'verification_uri', etc.

Exception Types

class MsalError(Exception):
    """Base exception for MSAL errors."""

class MsalServiceError(MsalError):
    """Exception for errors from identity service."""
    def __init__(self, *args, error: str, error_description: str, **kwargs): ...

class IdTokenError(RuntimeError):
    """Exception for ID token validation errors."""

class IdTokenIssuerError(IdTokenError):
    """Exception for ID token issuer validation errors."""

class IdTokenAudienceError(IdTokenError):
    """Exception for ID token audience validation errors."""

class IdTokenNonceError(IdTokenError):
    """Exception for ID token nonce validation errors."""

class BrowserInteractionTimeoutError(RuntimeError):
    """Exception for browser interaction timeout."""

class ManagedIdentityError(ValueError):
    """Exception for managed identity errors."""

class ArcPlatformNotSupportedError(ManagedIdentityError):
    """Exception for unsupported Azure Arc platforms."""