function get_access_token
Obtains an OAuth access token using MSAL (Microsoft Authentication Library) by first attempting to retrieve a cached token, then falling back to device code flow authentication if needed.
/tf/active/vicechatdev/mailsearch/example_script.py
27 - 48
moderate
Purpose
This function handles Microsoft identity platform authentication for public client applications. It implements a two-tier authentication strategy: first checking for cached tokens to avoid unnecessary re-authentication, and if that fails, initiating an interactive device code flow where users authenticate via a browser using a displayed code. This is particularly useful for CLI applications, scripts, or environments without a web browser where traditional OAuth flows are impractical.
Source Code
def get_access_token(app: msal.PublicClientApplication, scopes):
# Try cached
accounts = app.get_accounts()
if accounts:
result = app.acquire_token_silent(scopes=scopes, account=accounts[0])
if result and "access_token" in result:
return result["access_token"]
# Device code flow
flow = app.initiate_device_flow(scopes=scopes)
if "user_code" not in flow:
raise RuntimeError("Failed to create device flow. Check app registration.")
print("To sign in, use a browser to open the page:")
print(flow["verification_uri"])
print("and enter the code:", flow["user_code"])
result = app.acquire_token_by_device_flow(flow)
if "access_token" not in result:
raise RuntimeError("Failed to obtain access token:", result.get("error_description"))
return result["access_token"]
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
app |
msal.PublicClientApplication | - | positional_or_keyword |
scopes |
- | - | positional_or_keyword |
Parameter Details
app: An instance of msal.PublicClientApplication that represents the registered Azure AD application. This object must be properly configured with client_id and authority before being passed to this function.
scopes: A list of permission scopes (strings) that the access token should grant. Examples include ['User.Read', 'Mail.Send']. These scopes must be configured in the Azure AD app registration and determine what resources the token can access.
Return Value
Returns a string containing the OAuth access token that can be used to authenticate API requests to Microsoft services. The token is a JWT (JSON Web Token) that includes claims about the authenticated user and granted permissions. If authentication fails at any stage, the function raises a RuntimeError instead of returning a value.
Dependencies
msal
Required Imports
import msal
Usage Example
import msal
# Configure the MSAL application
client_id = 'your-client-id-here'
authority = 'https://login.microsoftonline.com/your-tenant-id'
scopes = ['User.Read']
# Create the public client application
app = msal.PublicClientApplication(
client_id=client_id,
authority=authority
)
# Get access token
try:
token = get_access_token(app, scopes)
print(f"Successfully obtained token: {token[:20]}...")
# Use the token to make API calls
headers = {'Authorization': f'Bearer {token}'}
# Make your API requests here
except RuntimeError as e:
print(f"Authentication failed: {e}")
Best Practices
- Always handle the RuntimeError exceptions that may be raised during authentication failures
- Store the returned access token securely and avoid logging it in plain text
- Access tokens have expiration times; implement token refresh logic for long-running applications
- Ensure the Azure AD app registration has device code flow enabled in the authentication settings
- Use appropriate scopes - request only the minimum permissions needed for your application
- The device code flow requires user interaction, so this function is not suitable for fully automated scenarios
- Consider implementing timeout handling for the device code flow as users may not complete authentication promptly
- Cache the MSAL PublicClientApplication instance rather than recreating it for each token request to benefit from token caching
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_ms365_token_v1 78.3% similar
-
function get_ms365_token 77.3% similar
-
function get_msal_app 74.7% similar
-
function get_o365_token 69.8% similar
-
function test_azure_token 69.8% similar