Search code examples
sharepointbearer-tokenazure-authentication

401 unauthorized: Access token validation failure calling Sharepoint


My goal is to get the list of sites with their web URL from REST API. I created one application in my tenant by granting it SharePoint API permissions.

I received the access token with client_credentials flow:

POST https://login.microsoft.com/864cc7c2-e44a-4a7e-bc1a-42b37ca38e66/oauth2/v2.0/token

client_id - 3affdc0e-04b4-495f-9346-7f5beda9c5ce,

grant_type - client_credentials,

client_secret - xxxxxx,

scope - https://< mytenant >.sharepoint.com/.default

But the issue is when I use that token to call the API. When I pass the Bearer token to call API, it's giving 401 unauthorized error like this:

{ 'error': { 'code': 'InvalidAuthenticationToken', 'message': 'Access token validation failure. Invalid Audience. ' } }

I think I messed up somewhere but don't know where in particular. Can anyone help me out?

But if I call the same in Microsoft Graph, I'm getting what I want which is very strange.


Solution

  • I tried to reproduce the same in my environment via Postman and got the below results:

    I created an Azure AD application and granted SharePoint permissions like this:

    enter image description here

    I generated the access token with same parameters as you like below:

    POST https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token
    

    Response:

    enter image description here

    When I tried to get the list of sites with their web URLs using below query, I got the same error:

    GET https://graph.microsoft.com/v1.0/sites?$select=webUrl,siteCollection
    

    Response:

    enter image description here

    To resolve the error, you need to do changes like below:

    Make sure to grant API permissions for Microsoft Graph instead of SharePoint like below:

    enter image description here

    Change the scope as https://graph.microsoft.com/.default to get access token like below:

    enter image description here

    Using the above token, I got the list of sites with their web URLs successfully like below:

    enter image description here

    Reference:

    List sites - Microsoft Graph v1.0 | Microsoft Docs