Microsoft Agents MSAL Authentication
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
-
ModuleNotFoundError: No module named 'agents'
cause Attempting to import `MSALAuthentication` directly from the top-level package name (`microsoft_agents_authentication_msal`) instead of its internal module path.fixChange your import statement from `from microsoft_agents_authentication_msal import MSALAuthentication` to `from agents.auth.msal import MSALAuthentication`. -
ValueError: Parameter 'client_id' is required.
cause The `MSALAuthentication` constructor was called without providing a `client_id` argument, or it was an empty string.fixPass a valid Azure AD application client ID when initializing: `MSALAuthentication(client_id="YOUR_AZURE_AD_CLIENT_ID")`. Ensure the client ID is not empty. -
MsalServiceException: AADSTS65001: The user or administrator has not consented to use the application with ID '...' named '...'. Send an interactive authorization request for this user and resource.
cause The Azure AD application lacks the necessary permissions, or user/admin consent has not been granted for the requested scopes.fixVerify that your Azure AD application is configured with the correct API permissions and that an administrator or user has granted consent. For Device Code Flow, ensure 'Allow public client flows' is enabled under Authentication settings. -
UserCancelledError: Authentication cancelled by user.
cause The user did not complete the device code flow in the browser within the allowed time, or explicitly cancelled the authentication.fixRe-run the authentication process and ensure the user navigates to the provided URL, enters the device code, and completes the sign-in/consent steps promptly in their web browser.
Warnings
- gotcha This library requires Python 3.10 or newer. Installing with older Python versions will lead to dependency resolution errors or runtime issues.
- breaking The import path `from microsoft_agents_authentication_msal import MSALAuthentication` is incorrect and will result in a `ModuleNotFoundError`.
- gotcha The `MSALAuthentication` class primarily implements the Device Code Flow, which requires user interaction in a web browser.
- gotcha A valid Azure AD application Client ID is essential for successful authentication. Using a placeholder or an invalid ID will cause errors.
Install
-
pip install microsoft-agents-authentication-msal
Imports
- MSALAuthentication
from microsoft_agents_authentication_msal import MSALAuthentication
from agents.auth.msal import MSALAuthentication
Quickstart
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.")