'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 1:[1]
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.
Solution 2:[2]
You can get the expiry time from the access token (usually at a field called exp and is formatted as unix timestamp). So whenever you prepare sending a HTTP request to the resource server , you can check that if the access token is already expired or about to be expired very soon (e.g 60 seconds).
If yes, try to use the refresh token to get a new access token , and update the returned new access token and refresh token that are stored inside your app. Otherwise , just keep using the existing access token.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tore Nestenius |
| Solution 2 |
