function test_sharepoint_with_token
Tests SharePoint REST API connectivity and authentication by making a GET request to retrieve site information using a provided access token.
/tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
126 - 149
simple
Purpose
This function is designed to validate SharePoint API access tokens by attempting to retrieve basic site information from a SharePoint site. It's useful for debugging authentication issues, testing different OAuth scopes, and verifying that tokens have the necessary permissions to access SharePoint resources. The function provides detailed console output including success/failure status, site title on success, and specific error messages for common authentication issues like 'Unsupported app only token' errors.
Source Code
def test_sharepoint_with_token(access_token, site_url, scope_name):
"""Test SharePoint API with a specific token."""
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json'
}
api_url = f"{site_url}/_api/web"
try:
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
print(f" ✅ SharePoint API call successful with {scope_name}")
try:
data = response.json()
print(f" Site title: {data.get('Title', 'Unknown')}")
except:
pass
else:
print(f" ❌ SharePoint API call failed with {scope_name}: {response.status_code}")
if response.status_code == 401 and "Unsupported app only token" in response.text:
print(" 💡 This scope also gets 'Unsupported app only token' error")
except Exception as e:
print(f" ❌ Exception testing SharePoint with {scope_name}: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
access_token |
- | - | positional_or_keyword |
site_url |
- | - | positional_or_keyword |
scope_name |
- | - | positional_or_keyword |
Parameter Details
access_token: A valid OAuth 2.0 access token (string) obtained from Azure AD/Microsoft Identity Platform that will be used in the Authorization header for authenticating the SharePoint API request. Should have appropriate SharePoint permissions.
site_url: The full URL (string) of the SharePoint site to test against, typically in the format 'https://{tenant}.sharepoint.com/sites/{sitename}' or 'https://{tenant}.sharepoint.com' for the root site. Should not include the '/_api/web' endpoint suffix.
scope_name: A descriptive name (string) identifying the OAuth scope or token type being tested. Used only for logging purposes to help identify which token/scope combination is being validated in the console output.
Return Value
This function does not return any value (implicitly returns None). All output is printed directly to the console, including success indicators (✅), failure indicators (❌), informational messages (💡), and the site title when successfully retrieved.
Dependencies
requestsjson
Required Imports
import requests
import json
Usage Example
import requests
import json
def test_sharepoint_with_token(access_token, site_url, scope_name):
headers = {
'Authorization': f'Bearer {access_token}',
'Accept': 'application/json'
}
api_url = f"{site_url}/_api/web"
try:
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
print(f" ✅ SharePoint API call successful with {scope_name}")
try:
data = response.json()
print(f" Site title: {data.get('Title', 'Unknown')}")
except:
pass
else:
print(f" ❌ SharePoint API call failed with {scope_name}: {response.status_code}")
if response.status_code == 401 and "Unsupported app only token" in response.text:
print(" 💡 This scope also gets 'Unsupported app only token' error")
except Exception as e:
print(f" ❌ Exception testing SharePoint with {scope_name}: {e}")
# Example usage
access_token = "eyJ0eXAiOiJKV1QiLCJhbGc..."
site_url = "https://contoso.sharepoint.com/sites/mysite"
scope_name = "Sites.Read.All"
test_sharepoint_with_token(access_token, site_url, scope_name)
Best Practices
- Ensure the access token is fresh and not expired before calling this function
- The site_url parameter should not include the '/_api/web' suffix as it's automatically appended
- This function prints output directly to console; consider modifying it to return structured data if integrating into larger applications
- Handle token refresh logic externally before calling this function
- Be aware that 'Unsupported app only token' errors indicate the token type (app-only vs delegated) is incompatible with the requested operation
- The function catches all exceptions broadly; consider more specific exception handling for production use
- Consider adding timeout parameters to the requests.get() call to prevent hanging on network issues
- For security, never log or print the actual access token value
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_sharepoint_api_call 92.0% similar
-
function test_sharepoint_token 87.3% similar
-
function test_azure_token 77.9% similar
-
function test_rest_client 76.2% similar
-
function test_graph_api_access 75.1% similar