🔍 Code Extractor

function get_ms365_token

Maturity: 51

Acquires an OAuth access token for Microsoft 365 using the MSAL library with client credentials flow for authenticating with Microsoft Graph API.

File:
/tf/active/vicechatdev/CDocs/utils/notifications.py
Lines:
412 - 444
Complexity:
moderate

Purpose

This function implements OAuth 2.0 client credentials flow to obtain an access token for Microsoft Graph API. It's designed for server-to-server authentication scenarios where an application needs to access Microsoft 365 resources without user interaction. The function creates a confidential client application, requests a token with the default Graph API scope, validates the token format, and returns it for use in subsequent API calls. It includes comprehensive error handling and logging for troubleshooting authentication issues.

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 .default scope for client credential flow
        result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
        
        if "access_token" in result:
            token = result["access_token"]
            # Validate token format
            if not isinstance(token, str) or not token.count('.') >= 2:
                logger.error(f"Received malformed token from MSAL: {token[:10]}...")
                return None
            logger.info("MS365 token acquired successfully")
            return 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 (JWT format with at least 2 dots separating header, payload, and signature) if successful, or None if token acquisition fails due to authentication errors, malformed token response, or exceptions. The token can be used in Authorization headers for Microsoft Graph API requests.

Dependencies

  • msal
  • logging

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 token
token = get_ms365_token()

if token:
    # Use the token in API requests
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    # Make Microsoft Graph API calls
    import requests
    response = requests.get(
        'https://graph.microsoft.com/v1.0/users',
        headers=headers
    )
    print(response.json())
else:
    print('Failed to acquire token')

Best Practices

  • Ensure Azure AD application is properly registered with client credentials flow enabled
  • Store MS365_CLIENT_SECRET securely using environment variables or secret management systems, never hardcode
  • Grant appropriate Microsoft Graph API application permissions (not delegated permissions) in Azure AD
  • Admin consent must be granted for application permissions in Azure portal
  • Implement token caching to avoid unnecessary token requests - MSAL has built-in token caching that can be leveraged
  • Handle None return value gracefully in calling code to prevent downstream errors
  • Monitor logs for authentication failures to detect configuration or permission issues
  • Token validation checks for JWT format (at least 2 dots) - consider additional validation if needed
  • The function uses client credentials flow suitable for daemon/service applications, not for user-interactive scenarios
  • Ensure network connectivity to login.microsoftonline.com and graph.microsoft.com endpoints

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_o365_token 87.7% similar

    Retrieves an OAuth 2.0 access token for Microsoft 365 using the client credentials flow to authenticate with Microsoft Graph API.

    From: /tf/active/vicechatdev/email-forwarder/src/utils/auth.py
  • function authenticate_o365 74.8% similar

    Authenticates with Microsoft Office 365 (O365) services by retrieving and returning an authentication token.

    From: /tf/active/vicechatdev/email-forwarder/src/utils/auth.py
  • function test_azure_token 67.7% similar

    Tests Azure AD authentication by attempting to acquire an OAuth2 access token using client credentials flow for Microsoft Graph API access.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function test_o365_connection 66.2% similar

    Tests the connection to Microsoft Office 365 (O365) by attempting to obtain an authentication token through the O365Client.

    From: /tf/active/vicechatdev/email-forwarder/test_service.py
  • class O365Client 65.8% similar

    A client class for interacting with Microsoft 365 Graph API to send emails with authentication, validation, and attachment support.

    From: /tf/active/vicechatdev/email-forwarder/src/forwarder/o365_client.py
← Back to Browse