🔍 Code Extractor

function test_graph_api_access

Maturity: 49

Tests Microsoft Graph API access by obtaining an OAuth2 token and verifying connectivity to check tenant settings for SharePoint integration.

File:
/tf/active/vicechatdev/SPFCsync/check_tenant_config.py
Lines:
25 - 67
Complexity:
moderate

Purpose

This function validates that the application can successfully authenticate with Microsoft Graph API using client credentials flow. It extracts the tenant name from a SharePoint URL, requests an access token from Azure AD, and then attempts to access Graph API endpoints to verify proper configuration. This is typically used as a diagnostic or setup verification step to ensure Azure app registration and permissions are correctly configured before attempting SharePoint operations.

Source Code

def test_graph_api_access():
    """Test if we can access Microsoft Graph API to check tenant settings."""
    config = load_config()
    if not config:
        return False
    
    site_url = config.get('SHAREPOINT_SITE_URL', '')
    client_id = config.get('AZURE_CLIENT_ID', '')
    client_secret = config.get('AZURE_CLIENT_SECRET', '')
    
    if '.sharepoint.com' in site_url:
        tenant = site_url.split('.sharepoint.com')[0].split('https://')[-1]
    else:
        print("❌ Cannot extract tenant from SharePoint URL")
        return False
    
    print("🔍 Testing Microsoft Graph API Access")
    print("=" * 40)
    
    # Get Graph token
    token_url = f"https://login.microsoftonline.com/{tenant}.onmicrosoft.com/oauth2/v2.0/token"
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': 'https://graph.microsoft.com/.default',
        'grant_type': 'client_credentials'
    }
    
    try:
        response = requests.post(token_url, data=data)
        if response.status_code == 200:
            token_data = response.json()
            access_token = token_data.get('access_token')
            print("✅ Successfully obtained Microsoft Graph token")
            
            # Try to get site information via Graph API
            return test_graph_sites_api(access_token, tenant)
        else:
            print(f"❌ Failed to get Graph token: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Exception getting Graph token: {e}")
        return False

Return Value

Returns a boolean value. Returns True if the Graph API token was successfully obtained and the subsequent Graph Sites API test passes (via test_graph_sites_api function). Returns False if any step fails, including: configuration loading failure, tenant extraction failure, token request failure, or exceptions during the process.

Dependencies

  • requests
  • json

Required Imports

import requests
import json

Usage Example

# Ensure load_config() and test_graph_sites_api() functions are available
# Ensure configuration file contains required Azure and SharePoint settings

# Example configuration (via load_config()):
# {
#   'SHAREPOINT_SITE_URL': 'https://contoso.sharepoint.com/sites/mysite',
#   'AZURE_CLIENT_ID': 'your-client-id-guid',
#   'AZURE_CLIENT_SECRET': 'your-client-secret'
# }

# Run the test
result = test_graph_api_access()

if result:
    print("Graph API access is properly configured")
else:
    print("Graph API access test failed - check configuration and permissions")

Best Practices

  • Ensure Azure AD application has appropriate Microsoft Graph API permissions (e.g., Sites.Read.All) before running this test
  • Store client secrets securely using environment variables or secure configuration management, never hardcode them
  • The function expects SharePoint URLs in the format 'https://{tenant}.sharepoint.com/...' - validate URL format before calling
  • This function has external dependencies on load_config() and test_graph_sites_api() functions which must be implemented separately
  • Handle the boolean return value appropriately in calling code to provide user feedback or take corrective action
  • Consider implementing retry logic for transient network failures when using in production
  • The function prints status messages directly - consider refactoring to use logging for production environments
  • Ensure the tenant name extraction logic matches your SharePoint URL structure (currently assumes .onmicrosoft.com domain)
  • Access tokens are short-lived - this function is intended for testing/validation, not for obtaining tokens for production use

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_azure_token 88.5% 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_sharepoint_token 84.8% similar

    Tests SharePoint OAuth2 authentication by acquiring an access token using client credentials flow and validates it with a SharePoint API call.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function test_graph_client 80.3% similar

    A test function that validates the SharePoint Graph API client by testing authentication, document listing, and file download capabilities.

    From: /tf/active/vicechatdev/SPFCsync/test_graph_client.py
  • function main_v44 79.9% similar

    Diagnostic function that tests SharePoint tenant configuration by checking Microsoft Graph API access and provides recommendations based on the results.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function test_graph_sites_api 79.6% similar

    Tests Microsoft Graph API access to SharePoint sites by attempting to list available sites and locate a specific target site (vicebio.com), then tests drive access if found.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
← Back to Browse