Microsoft Authentication Library for Python enabling OAuth2/OIDC authentication with Microsoft identity platform
npx @tessl/cli install tessl/pypi-msal@1.33.0The 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.
pip install msalpip install msal[broker]import msalCommon imports for different application types:
from msal import PublicClientApplication, ConfidentialClientApplicationToken caching imports:
from msal import TokenCache, SerializableTokenCacheManaged identity imports:
from msal import ManagedIdentityClient, SystemAssignedManagedIdentity, UserAssignedManagedIdentityVersion information:
import msal
print(msal.__version__) # "1.33.0"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')}")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')}")MSAL Python follows the OAuth2/OIDC protocol specifications with Microsoft identity platform extensions:
The library handles protocol complexities like token refresh, scope validation, and error handling while providing a simple, consistent API across different authentication scenarios.
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): ...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
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): ...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): ...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
): ...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
# 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.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."""