NinetyHH
NinetyHH

Reputation: 1464

Microsoft Graph returns 401 even if I have a valid access token

Currently I am trying to get all outlook user calendar events. I have followed all the instructions to set up Azure Active Directory V 2.0 and I am getting the access token doing:

Office.context.auth.getAccessTokenAsync(
    {
      allowConsentPrompt: true,
      allowSignInPrompt: true,
    },
   (result) => {
      if (result.status === 'succeeded') {
        return result.value
      }

      return result.error
    },
  )

After this, I am trying to get user calendar events by doing:

fetch(
`https://graph.microsoft.com/v1.0/me/events`,
{
  method: 'GET',
  headers: {
    Authorization: `Bearer ${accessToken}`,
    'Access-Control-Allow-Credentials': true,
    'access-control-allow-origin': 'my.domain',
    'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
    Prefer: 'outlook.timezone',
  }
}

)

In the end, I get a response 401 with the body:

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "request-id": "1fba5937-3106-460c-98a6-a1e7858b8116",
      "date": "2020-02-12T13:59:21"
    }
  }
}

I am currently stucked, I also tried to use instead of graph.microsoft.com to use the Office.context.mailbox.restUrl but that one does not accept the access token I have. Do I maybe skip something obvious?

PS: I forgot to mention that the scope permissions I gave to my add-in:

<Scopes>
      <Scope>user.read</Scope>
      <Scope>profile</Scope>
      <Scope>openid</Scope>
      <Scope>email</Scope>
      <Scope>offline_access</Scope>
      <Scope>files.read.all</Scope>
      <Scope>calendars.read</Scope>
    </Scopes>

Thank you

Upvotes: 0

Views: 676

Answers (1)

Jason Johnston
Jason Johnston

Reputation: 17692

Invalid audience means that the token you have was issued for an API other than the one you are calling. If you copy the token and head over to https://jwt.ms, you can parse it and examine the aud claim. If it is not https://graph.microsoft.com, you can't use it to call Microsoft Graph.

Upvotes: 3

Related Questions