SwagiWagi
SwagiWagi

Reputation: 441

Get an access token to Sharepoint and GraphAPI

I'd like to access both the Sharepoint Rest API and the GraphAPI using an access token acquired using the MSAL.js library.

I always get Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown. On Sharepoint though.

How can I acquire 2 access tokens (one for Sharepoint one for Graph)?

This is my current authentication flow: enter image description here

This is my current config in Azure: enter image description here

Upvotes: 1

Views: 7177

Answers (2)

Nikolay
Nikolay

Reputation: 12245

You seem to be using the default scopes, which is probably not what you want in case of SharePoint (you have not specified the scopes at all). BTW, looking at your app configuration, you seem to be not using graph api at all (scopes "openid" and "profile" are not exactly graph scopes, they are just openid scopes, even though they are listed under "graph" group). So assuming you have configuration like this:

const msalConfig = {
  auth: {
    <whatever>
    authority: "https://login.microsoftonline.com/<YOURDOMAIN>.onmicrosoft.com",
  }
}

For accessing SharePoint, use the SharePoint scopes (this is important, or otherwise you'll get the "AudienceUriValidationFailedException"):

const silentRequest = {
   <whatever>,
   scopes: ["https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]
}

const request = {
   <whatever>,
   scopes: ["https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]
}

There is also "https://<YOURDOMAIN>.sharepoint.com/.default" to go for all scopes you have in the app registration. In your case, it does not seem to matter because you are asking for the highest access level possible anyway (full control).

Note: as far as I know, you cannot mix the scope "types", i.e. the following will not work (trying to get a token that would be suitable to read user profile using graph api and access SharePoint at the same time):

scopes: ["User.Read", "https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl"]

In case you want to call both graph and "specific" API such as SharePoint or DevOps API for example, you need to get two separate tokens, i.e. make two calls, one for "User.Read" and another for "https://<YOURDOMAIN>.sharepoint.com/AllSites.FullControl". In your case, it also does not matter because it looks you don't to need the graph api access at all.

Also, to access SharePoint, you can use the awesome pnpjs library, it can be easily configured to be used with MSAL as well: https://pnp.github.io/pnpjs/authentication/msaljsclient/#calling-sharepoint-via-msal

Upvotes: 3

Chris Johnson
Chris Johnson

Reputation: 1350

You need to swap your graph auth token for one that will work with the SharePoint REST API.

I detailed the process here: https://stackoverflow.com/a/63386756/26843

Upvotes: 0

Related Questions