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 any exceptions during the 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 credentials securely using environment variables or secure configuration management
- The SharePoint URL must be in the format 'https://{tenant}.sharepoint.com/...' for tenant extraction to work
- This function prints sensitive information to console - use only in development/testing environments
- The function assumes tenant naming follows '{tenant}.onmicrosoft.com' convention
- Consider implementing token caching for production use rather than requesting new tokens for each operation
- Ensure the Azure AD application has been granted admin consent for the required Microsoft Graph API permissions
- The scope 'https://graph.microsoft.com/.default' requests all permissions configured for the application
- Handle the boolean return value appropriately in calling code to determine next steps
- Network connectivity to login.microsoftonline.com is required for this function to work
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_sharepoint_token 91.1% similar
-
function test_graph_api_access 88.4% similar
-
function test_different_scopes 78.7% similar
-
function test_sharepoint_with_token 78.0% similar
-
function test_sharepoint_api_call 77.0% similar