Share via

401 InvalidAuthenticationToken after token refresh

Luke 0 Reputation points
2023-09-08T16:47:37.9133333+00:00

I am using the msgraph-sdk-javascript and have implemented a custom getAccessToken handler. This handler checks whether the user's access token has expired, and if so, posts to the MSGraph /token endpoint to get a new access_token, refresh_token, and expires_in time.

In another function (doWork), I attempt to process a request to the graph api up to 3 times. If the request fails 3 times, I end the user's connection and log some information for debugging. However, if a user's access token is expired when doWork is called, there appears to be a chance that the response to the endpoint is a 401 InvalidAuthenticationToken which triggers doWork to be called again and loops until it fails with the same error 3 times.


What have I already investigated:

  1. I have verified to the best of my ability that the refresh token is valid. If I were to change it manually to make it invalid, I get an error about the refresh token being invalid when posting to /token.
  2. As far as I can tell, the call to /token does not fail - I have it wrapped in a try/catch and never get in the catch block.
  3. I have verified that the middleware (aka my custom getAccessToken) is being called via the sdk client whenever this error is thrown.
  4. I have verified that if I let a user do a fresh authentication (for a new access_token) and manually change the token to one I know is expired after a couple requests, my handler properly refreshes the token and continues without erroring in the doWork loop.

Seeing as how this is an error that is inconsistent (it only appears for users sometimes), and I can tell my handlers are being called, what would be the next steps in how to resolve this issue? Is there anything else that could cause a 401 I should be looking at?

Possible related issue: https://learn.microsoft.com/en-us/answers/questions/1290165/401-invalidauthenticationtoken-access-token-has-ex

// error thrown in doWork() 3 times
{
	statusCode: 401, 
	code: 'InvalidAuthenticationToken', 
	body: '{"code":"InvalidAuthenticationToken","message":"Access token has expired or is not yet valid"}'
}
Microsoft Security | Microsoft Graph
0 comments No comments

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-09-08T20:50:39.43+00:00

    Hi Luke,

    Thanks for reaching out. For Graph SDK related issues I would suggest posting the issue on the respective Graph SDK Github forum.

    Thanks.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.