function test_graph_api_access
Tests Microsoft Graph API access by obtaining an OAuth2 token and verifying connectivity to check tenant settings for SharePoint integration.
/tf/active/vicechatdev/SPFCsync/check_tenant_config.py
25 - 67
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
requestsjson
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 use
- 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 trigger error handling
- The function prints diagnostic messages to stdout - consider redirecting or capturing output in production environments
- Token obtained is not cached or returned - if needed for subsequent operations, consider refactoring to return the token
- Network timeouts and connection errors should be handled by the calling code or by adding timeout parameters to requests.post()
- The tenant extraction logic assumes a specific URL format - validate SharePoint URL structure in your environment
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_azure_token 88.4% similar
-
function test_sharepoint_token 83.1% similar
-
function test_graph_client 80.3% similar
-
function main_v26 79.9% similar
-
function test_graph_sites_api 79.6% similar