### Installing Dependencies from requirements.txt Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/dependency-management.md Use this command to install all dependencies listed in the `requirements.txt` file. This is crucial for recreating a consistent production environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### Verify Installation Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASE_GUIDE.md After a successful release, verify that the package can be installed using pip with the specific version. ```bash pip install msal==1.35.0 ``` -------------------------------- ### Install Development Code on Debian/Ubuntu Source: https://github.com/azuread/microsoft-authentication-library-for-python/wiki/How-to-test-an-Azure-CLI-branch-with-an-MSAL-branch Installs Python 3, creates a directory, clones the development branches of Azure CLI and MSAL Python, sets up a virtual environment, and installs necessary packages. Use this for Debian/Ubuntu systems. ```bash sudo apt install python3 python3-venv mkdir mi cd mi git clone https://github.com/jiasli/azure-cli --branch mi --depth 1 git clone https://github.com/AzureAD/microsoft-authentication-library-for-python --branch mi --depth 1 python3 -m venv env . env/bin/activate pip install azdev pip install -e microsoft-authentication-library-for-python[broker] azdev setup -c az --login ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/tests/README.md Sets up a Python virtual environment and installs project dependencies. Ensure you are in the repository root. ```powershell python -m venv .venv .\.venv\Scripts\Activate.ps1 python -m pip install --upgrade pip python -m pip install -r requirements.txt ``` -------------------------------- ### Username and Password Authentication Example Source: https://github.com/azuread/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication This snippet demonstrates how to acquire a token using a username and password. Ensure you have the necessary permissions and consider the security implications of storing and using credentials. ```python from msal import PublicClientApplication authority = "https://login.microsoftonline.com/common" client_id = "YOUR_CLIENT_ID" username = "user@yourdomain.com" password = "user_password" app = PublicClientApplication(client_id, authority=authority) result = app.acquire_token_by_username_password(username, password, scopes=["https://graph.microsoft.com/.default"]) if "access_token" in result: print("Access Token Acquired:") print(result["access_token"]) else: print("Error acquiring token:") print(result.get("error_description")) ``` -------------------------------- ### Generating requirements.txt with Pip Freeze Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/dependency-management.md After installing dependencies in a virtual environment, use `pip freeze` to generate a `requirements.txt` file. This file lists all installed packages and their exact versions, including transitive dependencies, enabling consistent environment recreation. ```bash pip freeze > requirements.txt ``` -------------------------------- ### Example Commit Message Structure Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/contributing.md Follow this structure for writing clear and informative commit messages. The first line is a short summary, followed by a blank line, and then a detailed explanation. ```git fix: explaining the commit in one line Body of commit message is a few lines of text, explaining things in more detail, possibly giving some background about the issue being fixed, etc etc. The body of the commit message can be several paragraphs, and please do proper word-wrap and keep columns shorter than about 72 characters or so. That way `git log` will show things nicely even when it is indented. ``` -------------------------------- ### NuGet Dependency Versioning Example Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASES.md This example shows how to specify a version range in NuGet for MSAL for .NET. The range '[1.1,1.2)' includes versions 1.1.x but excludes 1.2.x, allowing for patch updates while preventing major version changes. ```xml ``` -------------------------------- ### PopAuthScheme for Proof-of-Possession Tokens Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Illustrates the setup for `PopAuthScheme` to acquire Proof-of-Possession tokens, which are cryptographically bound to a specific HTTP request for enhanced security. Note that POP requires a broker on Windows and Mac. ```python import msal app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", enable_broker_on_windows=True, # POP requires broker on Windows/Mac # enable_broker_on_mac=True, ) ``` -------------------------------- ### Install msal-msiv2 Python Package Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/spikes/prototype/2026_MS_SecurityHackathon_MSIV2.md Install the 'msal-msiv2' package, which provides Managed Identity v2 support for Python applications. Ensure you use the specified version for compatibility. ```bash pip install msal-msiv2==1.35.0rc3 ``` -------------------------------- ### Managed Identity Client with MSAL Python Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt This example demonstrates how to use the `ManagedIdentityClient` to acquire tokens using Azure Managed Identity. It supports both system-assigned and user-assigned identities across various Azure services. ```python import msal import requests import json # System-assigned managed identity managed_identity = msal.SystemAssignedManagedIdentity() # Or user-assigned managed identity (choose one identifier) # managed_identity = msal.UserAssignedManagedIdentity(client_id="your_mi_client_id") # managed_identity = msal.UserAssignedManagedIdentity(resource_id="/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/your_mi") # managed_identity = msal.UserAssignedManagedIdentity(object_id="your_mi_object_id") # Create managed identity client with HTTP client that has retry logic session = requests.Session() from requests.adapters import HTTPAdapter, Retry retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[429, 500, 502, 503, 504]) session.mount("https://", HTTPAdapter(max_retries=retries)) client = msal.ManagedIdentityClient( managed_identity, http_client=session, token_cache=msal.TokenCache(), # Optional: enable caching ) ``` -------------------------------- ### Pinning a Specific Dependency Version with Pip Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/dependency-management.md Use this command to install a specific version of a package, ensuring consistency in your application's dependencies. Replace 'x.y.z' with the desired version number. ```bash pip install PackageName==x.y.z ``` -------------------------------- ### Acquire Token with Managed Identity v2 Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/spikes/prototype/2026_MS_SecurityHackathon_MSIV2.md Use MSAL Python to acquire a token for a resource using a system-assigned managed identity. This example demonstrates setting mtls_proof_of_possession and with_attestation_support. ```python import msal client = msal.ManagedIdentityClient( msal.SystemAssignedManagedIdentity(), ) result = client.acquire_token_for_client( resource="https://graph.microsoft.com", mtls_proof_of_possession=True, with_attestation_support=True, ) print(f"Token Type: {result['token_type']}") # mtls_pop print(f"Certificate: {result['cert_pem']}") print(f"Thumbprint: {result['cert_thumbprint_sha256']}") ``` -------------------------------- ### Call Protected Web API with Access Token Source: https://github.com/azuread/microsoft-authentication-library-for-python/wiki/Using-the-acquired-token-to-call-a-protected-Web-API Use the obtained access token in the 'Authorization' header as a 'Bearer' token when making requests to a protected Web API. This example uses the Requests library. ```python endpoint = "url to the API" http_headers = {'Authorization': 'Bearer ' + result['access_token'], 'Accept': 'application/json', 'Content-Type': 'application/json'} data = requests.get(endpoint, headers=http_headers, stream=False).json() ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/tests/README.md Defines necessary environment variables for local testing, particularly for E2E tests using lab secrets. The `.env` file is automatically loaded if `python-dotenv` is installed. ```dotenv LAB_APP_CLIENT_ID= LAB_APP_CLIENT_CERT_PFX_PATH=C:/path/to/your/cert.pfx ``` -------------------------------- ### Initialize PublicClientApplication Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/README.md Create an instance of PublicClientApplication for public client applications. Ensure you replace 'your_client_id' and 'Enter_the_Tenant_Name_Here' with your specific values. ```python from msal import PublicClientApplication app = PublicClientApplication( "your_client_id", authority="https://login.microsoftonline.com/Enter_the_Tenant_Name_Here") ``` -------------------------------- ### Quick Reference: Create Version Branch Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASE_GUIDE.md A quick command sequence to ensure `dev` is ready, bump the version, and create the release branch, which automatically triggers a TestPyPI publish. ```bash # 1. Ensure dev is ready, version bumped in msal/sku.py # 2. Cut version branch git checkout dev && git pull git checkout -b release-1.35.0 git push origin release-1.35.0 # → TestPyPI publish happens automatically ``` -------------------------------- ### Create GitHub Release Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASE_GUIDE.md Create a new release on GitHub. This process automatically triggers a PyPI publish. ```bash # 4. Production release: create a GitHub Release # → GitHub.com → Releases → New release # → Tag: 1.35.0, Target: release-1.35.0 # → PyPI publish happens automatically ``` -------------------------------- ### Configure HTTP Cache for MSAL Application Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Set up an HTTP cache using Python's `pickle` module to store and retrieve HTTP responses. This reduces network calls for metadata. The cache is loaded on startup and saved on exit. ```python import msal import pickle import os import atexit import logging # Load or create HTTP cache http_cache_file = "msal_http_cache.bin" try: with open(http_cache_file, "rb") as f: http_cache = pickle.load(f) except (FileNotFoundError, pickle.UnpicklingError, AttributeError): http_cache = {} # Start fresh # Save HTTP cache on exit def save_http_cache(): try: with open(http_cache_file, "wb") as f: pickle.dump(http_cache, f) except Exception: logging.exception("Failed to save HTTP cache") atexit.register(save_http_cache) # Create application with HTTP cache app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", http_cache=http_cache, # Caches instance discovery and other metadata token_cache=msal.SerializableTokenCache(), # Separate token cache ) ``` -------------------------------- ### Define Package Version Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASE_GUIDE.md The package version is defined in `msal/sku.py`. `setup.cfg` reads this dynamically. ```python __version__ = "x.y.z" ``` -------------------------------- ### Device Code Flow Initialization Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Initializes a PublicClientApplication for device code flow, enabling authentication on devices with limited input capabilities. Requires client ID and authority. ```python import msal import requests import json import sys app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", ) scopes = ["User.Read"] ``` -------------------------------- ### Create Release Branch Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASE_GUIDE.md Checkout the `dev` branch, pull the latest changes, and create a new release branch. This push automatically triggers a TestPyPI publish. ```bash git checkout dev git pull origin dev git checkout -b release-1.35.0 git push origin release-1.35.0 ``` -------------------------------- ### Run Unit and Integration Tests Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/tests/README.md Executes all tests except for E2E tests. Use the `-q` flag for quieter output. ```powershell python -m pytest -q tests -k "not e2e" ``` -------------------------------- ### Initiate Device Flow with MSAL Python Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Use this snippet to initiate a device flow for applications that do not have easy access to a browser. It displays a code to the user and prompts them to authenticate on a separate device. ```python import msal import sys import requests import json # Placeholder for app initialization and scopes # app = msal.PublicClientApplication(...) # scopes = [...] flow = app.initiate_device_flow(scopes=scopes) if "user_code" not in flow: raise ValueError(f"Failed to create device flow: {json.dumps(flow, indent=2)}") # Display instructions to user print(flow["message"]) sys.stdout.flush() # Block until user completes authentication (or timeout) result = app.acquire_token_by_device_flow(flow) if "access_token" in result: print(f"\nAuthentication successful!") print(f"Token source: {result.get('token_source')}") # Use the token response = requests.get( "https://graph.microsoft.com/v1.0/me", headers={"Authorization": f"Bearer {result['access_token']}"} ) user_info = response.json() print(f"Signed in as: {user_info.get('displayName')}") else: print(f"Authentication failed: {result.get('error')}") print(f"Description: {result.get('error_description')}") ``` -------------------------------- ### Run Full E2E Unattended Test Suite Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/tests/README.md Executes the complete unattended E2E test suite. Use the `-q` flag for quieter output. ```powershell python -m pytest -q tests/test_e2e.py ``` -------------------------------- ### Fork and Clone Repository Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/contributing.md Clone your forked repository and add the upstream remote to sync with the original project. ```bash $ git clone git@github.com:username/project-foo.git $ cd project-foo $ git remote add upstream git@github.com:AzureAD/project-foo.git ``` -------------------------------- ### Serializable Token Cache Management Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Demonstrates how to use SerializableTokenCache for persistent token storage. It loads an existing cache from a file, registers a function to save the cache on exit, and creates an application with the persistent cache. ```python import msal import os import atexit # Define cache file location cache_file = os.path.join( os.getenv("XDG_RUNTIME_DIR", os.path.expanduser("~")), "msal_token_cache.json" ) # Create serializable cache cache = msal.SerializableTokenCache() # Load existing cache from file if os.path.exists(cache_file): with open(cache_file, "r") as f: cache.deserialize(f.read()) # Register save on exit (only if cache changed) def save_cache(): if cache.has_state_changed: with open(cache_file, "w") as f: f.write(cache.serialize()) atexit.register(save_cache) # Create application with the persistent cache app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", token_cache=cache, ) # Use the application - tokens will be cached and persisted accounts = app.get_accounts() if accounts: result = app.acquire_token_silent(["User.Read"], account=accounts[0]) if result and "access_token" in result: print(f"Token retrieved from cache: {result.get('token_source')}") ``` -------------------------------- ### Acquire POP Token with MSAL Python Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Demonstrates acquiring a POP token for a specific request. Ensure POP is supported by the application and the target API. ```python import msal # Check if POP is supported if app.is_pop_supported(): # Create POP auth scheme for a specific request auth_scheme = msal.PopAuthScheme( http_method=msal.PopAuthScheme.HTTP_GET, url="https://api.example.com/resource", nonce="nonce_from_resource_challenge", # From WWW-Authenticate header ) accounts = app.get_accounts() if accounts: # Acquire POP token silently result = app.acquire_token_silent( scopes=["api://resource/.default"], account=accounts[0], auth_scheme=auth_scheme, ) # Or acquire interactively if not result: result = app.acquire_token_interactive( scopes=["api://resource/.default"], parent_window_handle=msal.PublicClientApplication.CONSOLE_WINDOW_HANDLE, auth_scheme=auth_scheme, ) if "access_token" in result: # The token_type will be "pop" instead of "Bearer" print(f"Token type: {result.get('token_type')}") else: print("POP tokens not supported on this platform") ``` -------------------------------- ### Enable Continuous Access Evaluation (CAE) with Client Capabilities Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Enables Continuous Access Evaluation (CAE) by declaring the 'CP1' client capability. This requires the identity platform and resource to support CAE. ```python import msal import requests # Enable CAE by declaring CP1 capability app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", client_capabilities=["CP1"], # Enables Continuous Access Evaluation ) scopes = ["User.Read"] accounts = app.get_accounts() result = None if accounts: result = app.acquire_token_silent(scopes, account=accounts[0]) if not result: result = app.acquire_token_interactive(scopes) if "access_token" in result: # Make API call response = requests.get( "https://graph.microsoft.com/v1.0/me", headers={"Authorization": f"Bearer {result['access_token']}"} ) # Handle claims challenge from resource if response.status_code == 401: www_authenticate = response.headers.get("WWW-Authenticate", "") # Parse claims challenge from header # claims_challenge = parse_claims_from_www_authenticate(www_authenticate) claims_challenge = '{"access_token":{"nbf":{"essential":true}}}' # Example # Re-acquire token with claims challenge result = app.acquire_token_silent( scopes, account=accounts[0], claims_challenge=claims_challenge, ) if not result or "error" in result: # Need interactive auth to satisfy claims result = app.acquire_token_interactive( scopes, claims_challenge=claims_challenge, ) ``` -------------------------------- ### Silent Token Acquisition with Error Handling Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Shows how to acquire tokens silently from the cache using both `acquire_token_silent` (returns None on failure) and `acquire_token_silent_with_error` (returns detailed error information). ```python import msal app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", ) scopes = ["User.Read"] accounts = app.get_accounts(username="user@example.com") if accounts: account = accounts[0] # Method 1: acquire_token_silent (returns None on failure) result = app.acquire_token_silent(scopes, account=account) if result: print(f"Silent acquisition succeeded: {result.get('token_source')}") else: print("Silent acquisition returned None - need interactive auth") # Method 2: acquire_token_silent_with_error (returns error details) result = app.acquire_token_silent_with_error( scopes, account=account, force_refresh=False, # Set True to skip cache and refresh token claims_challenge=None, # Pass claims challenge from resource if needed ) if result is None: print("No token in cache") elif "error" in result: print(f"Token refresh failed: {result.get('error')}") print(f"Description: {result.get('error_description')}") print(f"Classification: {result.get('classification')}") # Helps decide next steps else: print(f"Token acquired: {result.get('token_source')}") expires_in = result.get("expires_in", 0) print(f"Expires in {expires_in} seconds") ``` -------------------------------- ### Client Applications Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/docs/index.rst MSAL Python provides classes for creating public and confidential client applications to authenticate users and obtain tokens. ```APIDOC ## Client Applications MSAL Python provides classes for creating public and confidential client applications to authenticate users and obtain tokens. ### PublicClientApplication .. autoclass:: msal.PublicClientApplication :members: .. autoattribute:: msal.PublicClientApplication.CONSOLE_WINDOW_HANDLE .. automethod:: __init__ ### ConfidentialClientApplication .. autoclass:: msal.ConfidentialClientApplication :members: ``` -------------------------------- ### Mermaid Diagram for MSI v2 Flow Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/spikes/prototype/2026_MS_SecurityHackathon_MSIV2.md This diagram illustrates the end-to-end flow for acquiring a token using MSI v2 with mTLS, including key generation, CSR building, IMDS communication, STS token request, and final verification. ```mermaid %%{init: { "theme": "base", "themeVariables": { "fontFamily": "ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial", "primaryTextColor": "#0b1020", "lineColor": "#44506a", "tertiaryColor": "#f7f9ff" } }}%% flowchart TD classDef client fill:#E3F2FD,stroke:#1E88E5,stroke-width:2px,color:#0D47A1; classDef secure fill:#E8F5E9,stroke:#43A047,stroke-width:2px,color:#1B5E20; classDef platform fill:#FFF3E0,stroke:#FB8C00,stroke-width:2px,color:#E65100; classDef identity fill:#F3E5F5,stroke:#8E24AA,stroke-width:2px,color:#4A148C; classDef verify fill:#FFEBEE,stroke:#E53935,stroke-width:2px,color:#B71C1C; classDef output fill:#E0F7FA,stroke:#00ACC1,stroke-width:2px,color:#006064; A["App / Client Code"]:::client --> B["NCrypt / KeyGuard
Generate non-exportable RSA key"]:::secure B --> C["Build PKCS#10 CSR
(DER encoding)"]:::client C --> D{"Attestation enabled?"}:::platform D -- Yes --> E["MAA / AttestationClientLib.dll
Collect attestation evidence"]:::platform E --> F["IMDS /issuecredential
CSR (+ optional attestation)"]:::identity D -- No --> F A --> G["IMDS /getplatformmetadata"]:::identity G --> F F --> H["IMDS response
Client cert + STS URL"]:::identity H --> I["Entra STS (ESTS) /token
mTLS + client_credentials
token_type=mtls_pop"]:::identity I --> J["PoP access token (mtls_pop)
Includes cnf.x5t#S256"]:::output J --> K["Verify binding
cnf.x5t#S256 == cert SHA-256 thumbprint"]:::verify K --> L["Call Resource API
Token + mTLS cert"]:::output ``` -------------------------------- ### Manage Accounts with get_accounts and remove_account Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Retrieves accounts from the token cache using `get_accounts` and removes a specific account using `remove_account`. Ensure the `client_id` and `authority` are correctly configured. ```python import msal app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", # enable_broker_on_windows=True, # If broker enabled, also signs out from broker ) # Get all accounts in cache all_accounts = app.get_accounts() print(f"Found {len(all_accounts)} account(s) in cache") for account in all_accounts: print(f" Username: {account.get('username')}") print(f" Home account ID: {account.get('home_account_id')}") print(f" Environment: {account.get('environment')}") # Filter accounts by username specific_accounts = app.get_accounts(username="user@example.com") # Sign out and remove an account if all_accounts: account_to_remove = all_accounts[0] print(f"Removing account: {account_to_remove.get('username')}") app.remove_account(account_to_remove) # Verify removal remaining_accounts = app.get_accounts() print(f"Remaining accounts: {len(remaining_accounts)}") ``` -------------------------------- ### Acquire Token from Azure AD Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/README.md If no suitable token is found in the cache, acquire a new token from Azure AD. Handle potential errors by checking the 'error' and 'error_description' fields in the result. ```python if not result: # So no suitable token exists in cache. Let's get a new one from AAD. result = app.acquire_token_by_one_of_the_actual_method(..., scopes=["User.Read"]) if "access_token" in result: print(result["access_token"]) else: print(result.get("error")) print(result.get("error_description")) print(result.get("correlation_id")) ``` -------------------------------- ### Create Feature Branch Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/contributing.md Create a new branch for your feature or bug fix. ```bash $ git checkout -b my-feature-branch ``` -------------------------------- ### Acquire Token for a Resource and Call API Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Acquires an access token for a specified resource using client credentials and then uses it to call an Azure Resource Manager API. Detects the managed identity source if running in Azure. ```python result = client.acquire_token_for_client(resource="https://management.azure.com") if "access_token" in result: print(f"Token acquired from: {result.get('token_source')}") # Call Azure Resource Manager API response = requests.get( "https://management.azure.com/subscriptions?api-version=2022-01-01", headers={"Authorization": f"Bearer {result['access_token]'}"} ) print(json.dumps(response.json(), indent=2)) else: print(f"Error: {result.get('error')}") print(f"Description: {result.get('error_description')}") # Detect managed identity source source = msal.managed_identity.get_managed_identity_source() if source == msal.managed_identity.APP_SERVICE: print("Running on Azure App Service") elif source == msal.managed_identity.DEFAULT_TO_VM: print("Running on Azure VM or unknown environment") ``` -------------------------------- ### Configure MSAL Python Logging Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Configures Python's standard logging module to debug MSAL authentication issues. Use `logging.DEBUG` for detailed logs, including PII if `enable_pii_log` is set to `True`. ```python import logging import msal # Enable DEBUG logging for MSAL logging.basicConfig(level=logging.DEBUG) # Or selectively enable MSAL logging logging.getLogger("msal").setLevel(logging.DEBUG) # For less verbose output, use INFO level # logging.getLogger("msal").setLevel(logging.INFO) # Enable PII logging for broker troubleshooting app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", enable_pii_log=True, # WARNING: Logs may contain personal information ) ``` -------------------------------- ### Configure Git User Information Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/contributing.md Set your global Git user name and email address. This is required for commits. ```bash $ git config --global user.name "J. Random User" $ git config --global user.email "j.random.user@example.com" ``` -------------------------------- ### Acquire mTLS PoP Token with MSI v2 in Python Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/spikes/prototype/2026_MS_SecurityHackathon_MSIV2.md Use the ManagedIdentityClient to acquire an mTLS Proof-of-Possession token. This flow triggers the MSI v2 process and can optionally include KeyGuard attestation for enhanced security. ```python import msal client = msal.ManagedIdentityClient( msal.SystemAssignedManagedIdentity(), ) # Acquire mTLS PoP token with certificate binding result = client.acquire_token_for_client( resource="https://graph.microsoft.com", mtls_proof_of_possession=True, # triggers MSI v2 flow with_attestation_support=True, # KeyGuard attestation ) # result["token_type"] == "mtls_pop" # result["cert_pem"] - client certificate ``` -------------------------------- ### Create Custom MSAL Logging Handler Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Implement a custom logging handler by inheriting from `logging.Handler` to process MSAL log entries. This allows integration with custom logging systems or for specific log handling logic. ```python import logging class MSALHandler(logging.Handler): def emit(self, record): log_entry = self.format(record) # Send to your logging system print(f"MSAL LOG: {log_entry}") msal_logger = logging.getLogger("msal") msal_logger.addHandler(MSALHandler()) msal_logger.setLevel(logging.DEBUG) ``` -------------------------------- ### Authorization Code Flow for Web Apps with MSAL Python Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt This code demonstrates the authorization code flow, suitable for web applications. It involves initiating the flow, redirecting the user for sign-in, and then exchanging the authorization code for tokens. ```python import msal app = msal.ConfidentialClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", client_credential="your_client_secret", ) # Step 1: Initiate auth code flow (typically in a login route) auth_code_flow = app.initiate_auth_code_flow( scopes=["User.Read"], redirect_uri="https://yourapp.com/callback", state="random_state_for_csrf_protection", # Optional but recommended prompt=msal.Prompt.SELECT_ACCOUNT, # Force account selection login_hint="user@example.com", # Optional: pre-fill username ) # Store auth_code_flow in session, redirect user to auth_code_flow["auth_uri"] auth_uri = auth_code_flow["auth_uri"] print(f"Redirect user to: {auth_uri}") # Step 2: Handle callback (in your callback route) # auth_response is the query string dict from the redirect auth_response = { "code": "authorization_code_from_callback", "state": "random_state_for_csrf_protection", # ... other params from callback } # Exchange auth code for tokens result = app.acquire_token_by_auth_code_flow( auth_code_flow, # Retrieved from session auth_response, ) if "access_token" in result: print(f"User authenticated successfully") # Store tokens, create session, etc. id_token_claims = result.get("id_token_claims", {}) print(f"User: {id_token_claims.get('preferred_username')}") else: print(f"Error: {result.get('error')}") ``` -------------------------------- ### Enable and Run Manual-Intervention E2E Tests Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/tests/README.md Enables and runs manual intervention E2E tests, which are skipped by default. Set the `RUN_MANUAL_E2E` environment variable to '1'. ```powershell $env:RUN_MANUAL_E2E = "1" python -m pytest -q tests/test_e2e_manual.py ``` -------------------------------- ### Rebase from Upstream Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/contributing.md Synchronize your local branch with the upstream repository using git rebase. ```bash $ git fetch upstream $ git rebase upstream/v0.1 # or upstream/master ``` -------------------------------- ### Bump Version for Next Development Cycle Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/RELEASE_GUIDE.md After a release, if the `dev` branch version hasn't been updated, open a PR to bump `msal/sku.py` to the next development version. ```python __version__ = "1.36.0" ``` -------------------------------- ### Public Client Application Authentication Flow Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Handles token acquisition for public client applications (desktop/mobile) using silent or interactive flows. Requires client ID and authority. Optionally enables broker for enhanced security. ```python import msal import requests import json # Create a long-lived PublicClientApplication instance app = msal.PublicClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", # Optional: Enable broker for enhanced security (Windows 10+, Mac, Linux) # enable_broker_on_windows=True, # enable_broker_on_mac=True, ) # Define scopes for the API you want to access scopes = ["User.Read"] # Step 1: Check cache for existing accounts accounts = app.get_accounts() result = None if accounts: # Try silent token acquisition first chosen_account = accounts[0] result = app.acquire_token_silent(scopes, account=chosen_account) if not result: # Step 2: Fall back to interactive authentication result = app.acquire_token_interactive( scopes, login_hint="user@example.com", # Optional: pre-fill username # parent_window_handle=msal.PublicClientApplication.CONSOLE_WINDOW_HANDLE, # Required if broker enabled ) # Step 3: Use the token if "access_token" in result: print(f"Token source: {result.get('token_source')}") # Call an API with the token response = requests.get( "https://graph.microsoft.com/v1.0/me", headers={"Authorization": f"Bearer {result['access_token']}"} ) print(json.dumps(response.json(), indent=2)) else: print(f"Error: {result.get('error')}") print(f"Description: {result.get('error_description')}") ``` -------------------------------- ### Check Token Cache and Acquire Token Silently Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/README.md Check if accounts exist in the cache and attempt to acquire a token silently for a chosen account. This method is recommended to automatically handle token refresh. ```python # We now check the cache to see # whether we already have some accounts that the end user already used to sign in before. accounts = app.get_accounts() if accounts: # If so, you could then somehow display these accounts and let end user choose print("Pick the account you want to use to proceed:") for a in accounts: print(a["username"]) # Assuming the end user chose this one chosen = accounts[0] # Now let's try to find a token in cache for this account result = app.acquire_token_silent(["your_scope"], account=chosen) ``` -------------------------------- ### Prompt Behavior Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/docs/index.rst The Prompt enum controls how the user is prompted for authentication. ```APIDOC ## Prompt .. autoclass:: msal.Prompt :members: .. autoattribute:: msal.Prompt.SELECT_ACCOUNT .. autoattribute:: msal.Prompt.NONE .. autoattribute:: msal.Prompt.CONSENT .. autoattribute:: msal.Prompt.LOGIN ``` -------------------------------- ### Exceptions Source: https://github.com/azuread/microsoft-authentication-library-for-python/blob/dev/docs/index.rst MSAL Python may raise IdTokenError for issues related to ID tokens. ```APIDOC ## Exceptions These are exceptions that MSAL Python may raise. You should not need to create them directly. You may want to catch them to provide a better error message to your end users. .. autoclass:: msal.IdTokenError :members: ``` -------------------------------- ### Confidential Client Application Authentication Flow Source: https://context7.com/azuread/microsoft-authentication-library-for-python/llms.txt Acquires tokens for confidential client applications (web apps/daemons) using client credentials flow. Supports client secret or certificate-based authentication. Requires client ID, authority, and credentials. ```python import msal import requests import json # Create ConfidentialClientApplication with client secret app = msal.ConfidentialClientApplication( client_id="your_client_id", authority="https://login.microsoftonline.com/your_tenant_id", client_credential="your_client_secret", # Alternative: Use certificate authentication # client_credential={ # "private_key_pfx_path": "/path/to/certificate.pfx", # "passphrase": "optional_passphrase", # "public_certificate": True, # Enable Subject Name/Issuer auth # }, ) # Acquire token for the application itself (client credentials flow) # Scopes must use /.default suffix for client credentials scopes = ["https://graph.microsoft.com/.default"] result = app.acquire_token_for_client(scopes=scopes) if "access_token" in result: print(f"Token acquired from: {result.get('token_source')}") # Call Microsoft Graph as the application response = requests.get( "https://graph.microsoft.com/v1.0/users", headers={"Authorization": f"Bearer {result['access_token']}"} ) print(json.dumps(response.json(), indent=2)) else: print(f"Error: {result.get('error')}") print(f"Description: {result.get('error_description')}") ```