function test_azure_token
Tests Azure AD authentication by attempting to acquire an OAuth2 access token using client credentials flow for Microsoft Graph API access.
/tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
29 - 77
moderate
Purpose
This function validates Azure AD configuration by performing a complete OAuth2 client credentials flow authentication test. It extracts the tenant name from a SharePoint URL, constructs the appropriate token endpoint, and attempts to obtain an access token using provided client credentials. The function provides detailed console feedback about the authentication process, including success/failure status and token metadata. It's primarily used for diagnostic and validation purposes to ensure Azure AD credentials are correctly configured before attempting actual SharePoint or Microsoft Graph operations.
Source Code
def test_azure_token():
"""Test getting an access token from Azure AD."""
config = load_config()
if not config:
return False
print("Testing Azure AD token acquisition...")
# Extract tenant from SharePoint URL
site_url = config.get('SHAREPOINT_SITE_URL', '')
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
# Token endpoint
token_url = f"https://login.microsoftonline.com/{tenant}.onmicrosoft.com/oauth2/v2.0/token"
# Request parameters
data = {
'client_id': config.get('AZURE_CLIENT_ID'),
'client_secret': config.get('AZURE_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()
print("✅ Successfully obtained access token from Azure AD")
print(f" Token type: {token_data.get('token_type', 'Unknown')}")
print(f" Expires in: {token_data.get('expires_in', 'Unknown')} seconds")
return True
else:
print(f"❌ Failed to get token. Status: {response.status_code}")
try:
error_data = response.json()
print(f" Error: {error_data.get('error', 'Unknown')}")
print(f" Description: {error_data.get('error_description', 'No description')}")
except:
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"❌ Exception during token request: {e}")
return False
Return Value
Returns a boolean value: True if the access token was successfully obtained from Azure AD (HTTP 200 response), False if authentication failed due to invalid credentials, network errors, configuration issues, or exceptions during the request process.
Dependencies
requests
Required Imports
import requests
Usage Example
# Ensure load_config() function is available and returns a dict with required keys
# Example config structure:
# {
# '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_azure_token()
if result:
print("Azure AD authentication is properly configured")
else:
print("Azure AD authentication failed - check credentials and configuration")
Best Practices
- Ensure the load_config() function is properly implemented and returns all required configuration keys
- Store Azure client secrets securely using environment variables or secure configuration management
- The SharePoint URL must follow the format 'https://{tenant}.sharepoint.com/...' for tenant extraction to work
- This function assumes the tenant domain is '{tenant}.onmicrosoft.com' - adjust if using custom domains
- The function requests 'https://graph.microsoft.com/.default' scope - ensure the Azure AD app has appropriate Graph API permissions granted
- Use this function for testing/validation purposes only, not for production token acquisition (no token caching or reuse)
- Monitor Azure AD sign-in logs if authentication fails to diagnose permission or configuration issues
- The function prints sensitive information to console - avoid using in production environments where logs may be exposed
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_sharepoint_token 92.1% similar
-
function test_graph_api_access 88.5% similar
-
function test_different_scopes 78.7% similar
-
function test_sharepoint_with_token 77.9% similar
-
function test_sharepoint_api_call 76.5% similar