Python code to access SP not working ('Either scp or roles claim need to be present in the token.')

Sophie Rowbotham 0 Reputation points
2024-05-22T00:01:00.1433333+00:00

Hi Experts,

I've registered an app in Azure with the following API permission via Microsoft Graph: Sites.Read.All and have admin consent.

The following code is returning this error (note hidden client ID, client secret, tenant ID and site url - these are all confirmed correct).

import requests
from msal import ConfidentialClientApplication  

client_id = 'XXX' 
client_secret = 'XXX' 
tenant_id = 'XXX' 
site_url = 'XXX'
 
def get_access_token():
    authority = f"https://login.microsoftonline.com/{tenant_id}"
    app = ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
    result = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    
    if "access_token" in result:
        return result['access_token']
    else:
        print("Error acquiring token:")
        print(result)
        return None

def get_sharepoint_data(query):
    access_token = get_access_token()
    if not access_token:
        return {"error": "Failed to acquire access token"}
    
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Accept': 'application/json'
    }
    url = f"https://graph.microsoft.com/v1.0/sites/{site_url}/search/query?querytext='{query}'"
    response = requests.get(url, headers=headers)
    return response.json()

query = "Your search query here"
response = get_sharepoint_data(query)
print(response)

'error': 'code': 'AccessDenied', 'message': 'Either scp or roles claim need to be present in the token.'
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,922 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ling Zhou_MSFT 14,295 Reputation points Microsoft Vendor
    2024-05-22T02:34:23.9266667+00:00

    Hi @Sophie Rowbotham,

    Thank you for posting in this community.

    After configuring permissions, you need to click grant admin consent button.

    enter image description here


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.