Search code examples
sharepointazure-active-directorymicrosoft-graph-apibearer-token

Access token for Sharepoint for Graph API does not work to read the file contents


I am using Access token to browse my files on sharepoint. However, I thought I would be able to read the contents of the files too using that but I land up in below error. Does anyone know how do I resolve this?

{"error_description":"Exception of type >'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}

# Define imports
import requests
import pathlib

# Copy access_token and specify the MS Graph API endpoint you want to call, e.g. 'https://graph.microsoft.com/v1.0/groups' to get all groups in your organization
#access_token = '{ACCESS TOKEN YOU ACQUIRED PREVIOUSLY}'

url = "https://graph.microsoft.com/v1.0/..../search(q='593218')/"
headers = {
  'Authorization': token_result['access_token']
}

consentfilecount=0
clientreportcount = 0
graphlinkcount = 0

while True:
    
    try:
      graph_result = requests.get(url=url, headers=headers)
      graph_result.raise_for_status()
    except:
      token_result = client.acquire_token_for_client(scopes=scope)
    
    headers = {
      'Authorization': token_result['access_token']
    }
    

    if ('value' in graph_result.json()):
      for list in graph_result.json()['value']:
        for ele in finalReportNames:
          if ele.lower() in list["name"].lower():
            clientreportcount +=1

#below does not work
                response = requests.get(list["webUrl"],headers={"Authorization": token_result['access_token']})
                print(response)
                print(list["name"])
                print(list["webUrl"])
                print(pathlib.Path(list["name"]).suffix)
            #print(graph_result.json())
          if('@odata.nextLink' in graph_result.json()):
            url = graph_result.json()['@odata.nextLink']
            graphlinkcount += 1
          else:
            break
    
    print(consentfilecount)

Solution

  • The error "Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException" usually occurs if the access token audience is not matching the request or the audience is not the expected value.

    As you are making use of Microsoft Graph API query to access SharePoint files, you have to generate and pass the Microsoft Graph access token.

    Add Microsoft Graph API application permissions in the Azure AD application:

    enter image description here

    Hence modify your code by generating token by using below code snippet:

    from msal import ConfidentialClientApplication
    import requests
    
    # Set the values for your application
    client_id = 'ClientID'
    client_secret = 'ClientSecret'
    tenant_id = 'TenantID'
    scope = ['https://graph.microsoft.com/.default']
    
    # Create a ConfidentialClientApplication object
    app = ConfidentialClientApplication(
        client_id=client_id,
        client_credential=client_secret,
        authority='https://login.microsoftonline.com/' + tenant_id
    )
    
    # Acquire a token for the client
    token_result = app.acquire_token_for_client(scopes=scope)
    
    # Get the access token from the token result
    access_token = token_result['access_token']
    
    print(access_token)
    

    enter image description here

    Make sure that when you decode the access the token, the aud must be https://graph.microsoft.com

    enter image description here

    If you want to query using SharePoint Rest API query, then generate the token by passing scope as https://microsoft.sharepoint.com/.default

    To search files, refer Use the Microsoft Search API to search OneDrive and SharePoint content - Microsoft Graph | Microsoft

    To get the file content, refer Download a file - Microsoft Graph v1.0 | Microsoft