function get_ms365_token_v1
Authenticates with Microsoft 365 using MSAL (Microsoft Authentication Library) and retrieves an OAuth access token for the Microsoft Graph API.
/tf/active/vicechatdev/CDocs single class/utils/notifications.py
377 - 403
moderate
Purpose
This function implements the OAuth 2.0 client credentials flow to obtain an access token for Microsoft 365 services. It creates a confidential client application using tenant ID, client ID, and client secret, then requests a token with default Microsoft Graph API scopes. This token can be used to make authenticated requests to Microsoft Graph API endpoints, such as sending emails via Mail.Send. The function handles errors gracefully and logs any authentication failures.
Source Code
def get_ms365_token():
"""
Get OAuth token for Microsoft 365 using MSAL.
Returns:
Access token for Microsoft Graph API
"""
try:
# Create MSAL app
app = msal.ConfidentialClientApplication(
settings.MS365_CLIENT_ID,
authority=f"https://login.microsoftonline.com/{settings.MS365_TENANT_ID}",
client_credential=settings.MS365_CLIENT_SECRET
)
# Get token with Mail.Send scope
result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
if "access_token" in result:
return result["access_token"]
else:
logger.error(f"Error getting MS365 token: {result.get('error')}, {result.get('error_description')}")
return None
except Exception as e:
logger.error(f"Error in get_ms365_token: {e}")
return None
Return Value
Returns a string containing the OAuth access token if authentication is successful, or None if an error occurs during token acquisition. The access token is a JWT (JSON Web Token) that can be used in the Authorization header for Microsoft Graph API requests. The token has a limited lifetime (typically 1 hour) and should be cached and refreshed as needed.
Dependencies
msallogging
Required Imports
import msal
import logging
Usage Example
# Ensure settings are configured
# settings.MS365_CLIENT_ID = 'your-client-id'
# settings.MS365_TENANT_ID = 'your-tenant-id'
# settings.MS365_CLIENT_SECRET = 'your-client-secret'
import logging
import msal
from your_config import settings
# Setup logger
logger = logging.getLogger(__name__)
# Get the access token
token = get_ms365_token()
if token:
# Use the token to make Microsoft Graph API requests
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
# Example: Send email via Graph API
# response = requests.post('https://graph.microsoft.com/v1.0/users/user@domain.com/sendMail', headers=headers, json=email_data)
else:
print('Failed to obtain access token')
Best Practices
- Store MS365 credentials (client ID, tenant ID, client secret) securely using environment variables or a secure configuration management system, never hardcode them
- Implement token caching to avoid unnecessary authentication requests, as tokens are valid for approximately 1 hour
- The function returns None on error, so always check the return value before using the token
- Ensure the Azure AD application has the necessary API permissions (e.g., Mail.Send) and that admin consent has been granted
- Monitor the logger output for authentication errors, which may indicate configuration issues or expired credentials
- Use the client credentials flow only for server-to-server authentication, not for user-delegated scenarios
- Consider implementing retry logic with exponential backoff for transient network errors
- The '.default' scope requests all permissions configured for the application in Azure AD
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_ms365_token 95.8% similar
-
function get_o365_token 87.6% similar
-
function get_access_token 78.3% similar
-
function authenticate_o365 76.6% similar
-
class O365Client 70.2% similar