Search code examples
sharepoint

How to call sharepoint api?


How do you call SharePoint API ?

I have a oauth2 login implemented with multi tenant option.

I request these scopes:

  • "openid"
  • "User.Read"
  • "email"
  • "Files.Read.All"
  • "Files.ReadWrite"
  • "Files.ReadWrite.All"
  • "Sites.Read.All"
  • "Sites.ReadWrite.All"
  • "https://mydomain.sharepoint.com/AllSites.Read"
  • "https://mydomain.sharepoint.com/MyFiles.Read"

I retrieve the access token using which i can access Graph API

but not SharePoint API, i get

Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException error.

Here they say you cannot access SPO with that access token but nobody explains why or how to get the correct one

I find microsoft documentation very lacking and what little it does exist, it's very hard to understand.


Solution

  • @Jackson The issue you're encountering is because there are differences between access tokens issued for Microsoft Graph API and those needed for the SharePoint REST API.

    When requesting an access token, you should specify the SharePoint site as the resource. your token request might look like:

    POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=client_credentials
    &client_id={client-id}
    &client_secret={client-secret}
    &scope=https://{tenant}.sharepoint.com/.default
    

    Do not use Sites.Read.All or Sites.ReadWrite.All, instead use .default as the scope when requesting a token for SharePoint. The .default scope will give you permissions based on what has been consented to in the Azure AD app registration for SharePoint. Finally, once you receive the access token with the correct audience, you can use it to make requests to the SharePoint REST API. The token should be passed in the Authorization header as a Bearer token.