🔍 Code Extractor

function get_o365_token

Maturity: 53

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

File:
/tf/active/vicechatdev/email-forwarder/src/utils/auth.py
Lines:
6 - 30
Complexity:
simple

Purpose

This function implements OAuth 2.0 client credentials authentication 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 token can be used to make authenticated requests to Microsoft Graph API endpoints for operations like reading emails, calendar events, or other Microsoft 365 data.

Source Code

def get_o365_token() -> str:
    """
    Retrieve an OAuth token for Microsoft 365 using client credentials.
    
    Returns:
        Access token for Microsoft Graph API.
    """
    token_url = f"https://login.microsoftonline.com/{settings.MS365_TENANT_ID}/oauth2/v2.0/token"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    body = {
        "client_id": settings.MS365_CLIENT_ID,
        "client_secret": settings.MS365_CLIENT_SECRET,
        "scope": "https://graph.microsoft.com/.default",
        "grant_type": "client_credentials"
    }
    
    try:
        response = requests.post(token_url, headers=headers, data=body)
        response.raise_for_status()
        token_data = response.json()
        return token_data['access_token']
    except RequestException as e:
        raise Exception(f"Failed to retrieve O365 token: {str(e)}")

Return Value

Type: str

Returns a string containing the OAuth 2.0 access token (JWT) that can be used in the Authorization header for Microsoft Graph API requests. The token is extracted from the 'access_token' field of the JSON response from Microsoft's token endpoint. Raises an Exception if the token retrieval fails due to network issues, authentication errors, or invalid credentials.

Dependencies

  • requests
  • typing

Required Imports

import requests
from requests.exceptions import RequestException
from CDocs.config import settings

Usage Example

# Ensure settings are configured with Microsoft 365 credentials
# from CDocs.config import settings
# settings.MS365_TENANT_ID = 'your-tenant-id'
# settings.MS365_CLIENT_ID = 'your-client-id'
# settings.MS365_CLIENT_SECRET = 'your-client-secret'

try:
    access_token = get_o365_token()
    print(f"Token obtained: {access_token[:20]}...")
    
    # Use the token to make Graph API requests
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    response = requests.get('https://graph.microsoft.com/v1.0/users', headers=headers)
    users = response.json()
except Exception as e:
    print(f"Error: {e}")

Best Practices

  • Store Microsoft 365 credentials securely using environment variables or secure configuration management, never hardcode them
  • Implement token caching to avoid unnecessary token requests, as tokens are typically valid for 60-90 minutes
  • Handle the Exception raised by this function appropriately in calling code to manage authentication failures gracefully
  • Ensure the Azure AD application has been granted the necessary API permissions in the Azure portal
  • Use HTTPS for all requests (already implemented in the function)
  • Consider implementing retry logic with exponential backoff for transient network failures
  • Monitor token expiration and refresh tokens proactively before they expire
  • The client credentials flow is suitable for daemon/service applications, not for user-delegated scenarios

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_ms365_token 87.7% 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 authenticate_o365 82.3% 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_o365_connection 74.6% 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 73.0% 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
  • function test_azure_token 68.2% 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
← Back to Browse