🔍 Code Extractor

function test_different_scopes

Maturity: 48

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.

File:
/tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
Lines:
70 - 124
Complexity:
moderate

Purpose

This diagnostic function validates Azure AD application permissions by testing multiple OAuth2 scopes (SharePoint-specific and Microsoft Graph) to determine which permissions are correctly configured. It helps troubleshoot authentication issues by attempting token acquisition with different scope configurations and testing the resulting tokens against SharePoint endpoints.

Source Code

def test_different_scopes():
    """Test different permission scopes."""
    config = load_config()
    if not config:
        return
    
    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
    
    print("🔍 Testing Different Permission Scopes")
    print("=" * 40)
    
    # Test different scopes
    scopes_to_test = [
        f"https://{tenant}.sharepoint.com/.default",
        "https://graph.microsoft.com/.default",
        f"https://{tenant}.sharepoint.com/Sites.Read.All"
    ]
    
    for scope in scopes_to_test:
        print(f"\nTesting scope: {scope}")
        token_url = f"https://login.microsoftonline.com/{tenant}.onmicrosoft.com/oauth2/v2.0/token"
        
        data = {
            'client_id': client_id,
            'client_secret': client_secret,
            'scope': scope,
            'grant_type': 'client_credentials'
        }
        
        try:
            response = requests.post(token_url, data=data)
            if response.status_code == 200:
                token_data = response.json()
                print(f"✅ Successfully got token for scope: {scope}")
                
                # Test the token with SharePoint
                access_token = token_data.get('access_token')
                test_sharepoint_with_token(access_token, site_url, scope)
            else:
                print(f"❌ Failed to get token for scope: {scope}")
                try:
                    error_data = response.json()
                    print(f"   Error: {error_data.get('error', 'Unknown')}")
                except:
                    pass
        except Exception as e:
            print(f"❌ Exception testing scope {scope}: {e}")

Return Value

No explicit return value. The function outputs diagnostic information to stdout, printing success/failure messages for each scope tested. Returns None implicitly, or returns early if configuration is invalid.

Dependencies

  • requests
  • json

Required Imports

import requests
import json

Usage Example

# Ensure load_config() and test_sharepoint_with_token() are defined
# Example config.json:
# {
#   "SHAREPOINT_SITE_URL": "https://contoso.sharepoint.com/sites/mysite",
#   "AZURE_CLIENT_ID": "your-client-id",
#   "AZURE_CLIENT_SECRET": "your-client-secret"
# }

import requests
import json

# Define required helper functions
def load_config():
    with open('config.json', 'r') as f:
        return json.load(f)

def test_sharepoint_with_token(token, site_url, scope):
    # Implementation to test token against SharePoint
    pass

# Run the scope testing
test_different_scopes()

# Output will show:
# 🔍 Testing Different Permission Scopes
# ========================================
# Testing scope: https://contoso.sharepoint.com/.default
# ✅ Successfully got token for scope: ...

Best Practices

  • Ensure load_config() function is implemented and returns a dictionary with required keys
  • Ensure test_sharepoint_with_token() function is implemented to validate acquired tokens
  • Store client secrets securely, never hardcode them in source code
  • The function expects SharePoint URLs in format 'https://{tenant}.sharepoint.com/...'
  • Function performs network requests and may take time; consider timeout handling in production
  • Error handling is basic; enhance for production use with proper logging
  • The function tests three different scope patterns - ensure Azure AD app has appropriate permissions configured
  • Tenant extraction logic assumes standard SharePoint URL format; may fail with custom domains
  • Consider rate limiting when testing multiple scopes to avoid throttling

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_sharepoint_token 79.8% similar

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

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function test_azure_token 78.7% 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_graph_api_access 76.9% 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 main_v47 76.5% similar

    Entry point function that runs a SharePoint permission diagnostic tool, testing different authentication scopes and providing troubleshooting guidance.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
  • function test_sharepoint_api_call 73.0% 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
← Back to Browse