Microsoft Agents MSAL Authentication

0.9.0 · active · verified Fri Apr 17

microsoft-agents-authentication-msal is a Python library providing MSAL-based authentication specifically for Microsoft Agents. It primarily implements the device code flow using MSAL to acquire authentication tokens. Currently at version 0.9.0, it's part of the broader Microsoft Agents framework and follows its release cadence, focusing on integrating with Microsoft services.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic authentication using the MSAL Device Code Flow. It initializes `MSALAuthentication` with a client ID and attempts to acquire an access token for the Microsoft Graph default scope. Note that this flow requires user interaction in a web browser.

import os
from agents.auth.msal import MSALAuthentication
from agents.auth.types import IAuthentication

# For demonstration, retrieve client_id from environment variable.
# In a real application, you would configure this securely.
CLIENT_ID = os.environ.get('MSAL_CLIENT_ID', 'YOUR_MSAL_CLIENT_ID_HERE')
if CLIENT_ID == 'YOUR_MSAL_CLIENT_ID_HERE':
    print("WARNING: Please set the MSAL_CLIENT_ID environment variable or replace 'YOUR_MSAL_CLIENT_ID_HERE' with your actual Azure AD application client ID.")

try:
    # Initialize MSAL authentication using Device Code Flow
    # This will print a URL and a device code that the user needs to enter in a browser.
    auth: IAuthentication = MSALAuthentication(client_id=CLIENT_ID)

    print(f"Attempting to get token with client_id: {CLIENT_ID}...")
    # Acquire a token for Microsoft Graph default scope
    # The actual scope might vary depending on the Microsoft Agent's requirements.
    # Common scopes include "https://graph.microsoft.com/.default" for broad Graph access.
    # Other scopes like "api://<your-app-id>/.default" might be used for custom APIs.
    token_response = auth.get_token(scope=["https://graph.microsoft.com/.default"])

    print("\nAuthentication successful!")
    print(f"Access Token (first 20 chars): {token_response.access_token[:20]}...")
    print(f"Expires On: {token_response.expires_on}")

except ValueError as e:
    print(f"Error during authentication setup: {e}")
    if "client_id" in str(e):
        print("Hint: Ensure MSAL_CLIENT_ID is correctly set and not empty.")
except Exception as e:
    print(f"An unexpected error occurred during token acquisition: {e}")
    print("Please check your network connection, client_id, and ensure you completed the device code flow in the browser.")

view raw JSON →