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

Anonymous
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.'
Microsoft 365 and Office SharePoint For business Windows
{count} vote

2 answers

Sort by: Most helpful
  1. Ling Zhou_MSFT 23,620 Reputation points Microsoft External Staff
    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.


  2. Kiah Jane Seki 0 Reputation points
    2025-02-20T14:03:35.5666667+00:00

    I run into the same issue despite having the required access roles. On other forums, I have read that this is a bug in the library. Are there any new updates?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.