PyMSALRuntime

0.20.2 · active · verified Tue Apr 14

PyMSALRuntime is the Python interop package for the Microsoft Authentication Library (MSAL) Runtime. It acts as a low-level bridge, enabling Python applications, primarily through the MSAL Python library, to interact with the underlying OS-level authentication broker for enhanced security and single sign-on experiences. The current version is 0.20.2, released on January 9, 2026, with frequent updates to align with the MSAL ecosystem.

Warnings

Install

Imports

Quickstart

PyMSALRuntime is an internal dependency of MSAL Python. The most common way to 'use' PyMSALRuntime is indirectly by enabling the authentication broker functionality in the MSAL Python library. This quickstart demonstrates how to acquire a token using `msal.PublicClientApplication` with `enable_broker=True`. When running on Windows or macOS, and a compatible broker is installed, `msal` will attempt to use PyMSALRuntime to interact with it, providing single sign-on capabilities and enhanced security. Ensure `MSAL_CLIENT_ID` is set as an environment variable or replaced directly. This code will attempt silent token acquisition and fall back to an interactive flow if needed.

import os
from msal import PublicClientApplication

# Configure your application
# You would typically get CLIENT_ID from your Azure AD application registration
# You might also need a 'tenant_id' or 'authority' depending on your scenario
CLIENT_ID = os.environ.get('MSAL_CLIENT_ID', 'YOUR_CLIENT_ID_HERE')
AUTHORITY = os.environ.get('MSAL_AUTHORITY', 'https://login.microsoftonline.com/common')

# Initialize a PublicClientApplication with broker enabled
# PyMSALRuntime is leveraged under the hood when 'enable_broker=True' on Windows/macOS
app = PublicClientApplication(CLIENT_ID, authority=AUTHORITY, enable_broker=True)

# Define the scope(s) for which you want to acquire a token
scopes = ['User.Read']

# Acquire a token silently (if a cached token exists and is valid)
result = app.acquire_token_silent(scopes, account=None)

if not result:
    # If no token is cached or it's expired, acquire it interactively (will open a browser/broker window)
    print("No cached token found or expired. Acquiring interactively...")
    flow = app.initiate_auth_code_flow(scopes=scopes)
    print(f"Please go to this URL and authorize: {flow['auth_uri']}")
    result = app.acquire_token_by_auth_code_flow(flow, {
        'code': input('Enter the authorization code: ')
    })

if 'access_token' in result:
    print("Access token acquired successfully!")
    print(f"Token expires on: {result.get('expires_on')}")
    # You can now use result['access_token'] to call protected APIs
else:
    print(f"Token acquisition failed: {result.get('error_description', result.get('error'))}")

view raw JSON →