🔍 Code Extractor

function get_ms365_token_v1

Maturity: 47

Authenticates with Microsoft 365 using MSAL (Microsoft Authentication Library) and retrieves an OAuth access token for the Microsoft Graph API.

File:
/tf/active/vicechatdev/CDocs single class/utils/notifications.py
Lines:
377 - 403
Complexity:
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

  • 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 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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_ms365_token 95.8% similar

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

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function get_o365_token 87.6% 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 get_access_token 78.3% similar

    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.

    From: /tf/active/vicechatdev/mailsearch/example_script.py
  • function authenticate_o365 76.6% 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
  • class O365Client 70.2% 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