function test_sharepoint_token
Tests SharePoint OAuth2 authentication by acquiring an access token using client credentials flow and validates it with a SharePoint API call.
/tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
79 - 143
moderate
Purpose
This function validates SharePoint authentication configuration by obtaining a SharePoint-specific access token from Azure AD using the OAuth2 client credentials grant type. It extracts the tenant from the SharePoint URL, requests an access token with appropriate scopes, and tests the token by making an API call to SharePoint. It provides detailed error diagnostics and troubleshooting guidance for common authentication failures.
Source Code
def test_sharepoint_token():
"""Test getting a SharePoint-specific access token."""
config = load_config()
if not config:
return False
print("\nTesting SharePoint-specific 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]
sharepoint_resource = f"https://{tenant}.sharepoint.com"
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 for SharePoint
data = {
'client_id': config.get('AZURE_CLIENT_ID'),
'client_secret': config.get('AZURE_CLIENT_SECRET'),
'scope': f'{sharepoint_resource}/.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 SharePoint access token")
print(f" Token type: {token_data.get('token_type', 'Unknown')}")
print(f" Expires in: {token_data.get('expires_in', 'Unknown')} seconds")
# Test the token with SharePoint API
access_token = token_data.get('access_token')
return test_sharepoint_api_call(access_token, site_url)
else:
print(f"ā Failed to get SharePoint 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')}")
# Provide specific guidance for common errors
error = error_data.get('error', '')
if 'invalid_client' in error:
print("\nš” This usually means:")
print(" - Client ID is incorrect")
print(" - Client secret is incorrect or expired")
elif 'unauthorized_client' in error:
print("\nš” This usually means:")
print(" - App registration doesn't have the right permissions")
print(" - Admin consent hasn't been granted")
except:
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"ā Exception during SharePoint token request: {e}")
return False
Return Value
Returns a boolean value: True if the SharePoint token was successfully obtained and validated through a SharePoint API call (via test_sharepoint_api_call function), False if token acquisition failed, configuration is missing, tenant extraction failed, or any exception occurred during the process.
Dependencies
requests
Required Imports
import requests
Usage Example
# Ensure load_config() and test_sharepoint_api_call() functions are defined
# Configuration file should contain:
# SHAREPOINT_SITE_URL = 'https://contoso.sharepoint.com/sites/mysite'
# AZURE_CLIENT_ID = 'your-client-id'
# AZURE_CLIENT_SECRET = 'your-client-secret'
result = test_sharepoint_token()
if result:
print('SharePoint authentication is properly configured')
else:
print('SharePoint authentication failed - check configuration and permissions')
Best Practices
- Ensure the Azure AD app registration has Sites.Read.All or Sites.ReadWrite.All permissions for SharePoint
- Admin consent must be granted for the application permissions in Azure AD
- Client secrets should be stored securely and rotated regularly
- The function depends on external functions (load_config and test_sharepoint_api_call) which must be implemented
- SharePoint URL must follow the format https://{tenant}.sharepoint.com for proper tenant extraction
- Token expiration should be monitored (typically 3600 seconds for client credentials flow)
- Error messages provide diagnostic information - review them carefully for troubleshooting
- The function uses synchronous requests - consider timeout parameters for production use
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_azure_token 91.1% similar
-
function test_sharepoint_with_token 88.1% similar
-
function test_sharepoint_api_call 83.8% similar
-
function test_graph_api_access 83.1% similar
-
function test_different_scopes 79.2% similar