Search code examples
oauth-2.0openid-connectrefresh-token

When to refresh the access token


My problem is figuring out when to refresh the access token.

I have read that I should refresh the new access token before each request, but it says elsewhere that this is not recommended. So my question is whether I should refresh the access token before each request or send the request and after receiving the 401 Unauthorized status refresh the access token and retry the request to the specified resource.


Solution

  • You can do either way, you know when you access token is about to expire and for example 1 minute before, you use the refresh token to get a new set of refresh/access tokens.

    Doing it on a 401 is also an option but that means that you need to do an extra request and you also have some race-conditions to watch out for, as in many configurations you only allow a one-time use of a refresh token (you get a new refresh token each time). So with the 401 approach, you need to make sure you don't sent away many concurrent requests to get new tokens for the same user.