šŸ” Code Extractor

function test_sharepoint_token

Maturity: 46

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

File:
/tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
Lines:
79 - 143
Complexity:
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 successful')
else:
    print('SharePoint authentication failed')

Best Practices

  • Ensure the Azure AD app registration has Sites.Read.All or Sites.FullControl.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 load_config() and test_sharepoint_api_call() helper functions which must be implemented
  • SharePoint URL must contain '.sharepoint.com' domain for tenant extraction to work
  • The function provides diagnostic output to stdout, making it suitable for interactive testing but not for silent automation
  • Token expiration time is displayed but the token is not cached - consider implementing token caching for production use
  • Error handling provides specific guidance for common authentication issues like invalid_client and unauthorized_client errors

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_azure_token 92.1% 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_with_token 87.3% similar

    Tests SharePoint REST API connectivity and authentication by making a GET request to retrieve site information using a provided access token.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
  • function test_graph_api_access 84.8% similar

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

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function test_sharepoint_api_call 83.9% similar

    Tests SharePoint REST API connectivity by making an authenticated GET request to retrieve basic site information and validates the access token and permissions.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function test_different_scopes 79.8% similar

    Tests OAuth2 authentication with different permission scopes for SharePoint and Microsoft Graph APIs, attempting to acquire access tokens and validate them against a SharePoint site.

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