Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
I am implementing OAuth for a project, and I want to know the best way to handle refresh tokens.
The API I call will return a JSON object with access_token, expires_in, and refresh_token.
So I was wondering, is it better to:
Calculate the time when the access_token will expire, store that in the database. Check that the access_token is not expired every time I make an API call, and if it is expired then use the refresh_token to get a new access_token.
(Additional Question: how do I make sure that the time which I calculate for the token expiration is accurate? Because the expire_in value probably starts from when the API server generated the key, and not when I receive it.)
OR
- Just try to make the API call with the access_token every time, and if that returns with an error then use the refresh_token.
I am also open to other options of implementing this.
The client should always be prepared to handle an error returned from the API that indicates that the access_token
validation failed. Depending on the implementation the access token may have been revoked or declared invalid otherwise.
The client may then use a refresh_token
to get a new access token and try again. So you can choose to implement 1. but it does not free you from implementing 2. as well, so you may choose to stick to only implementing 2 and minimize the amount of code required.
Of course if you want to prevent errors from happening as much as possible you could implement 1. to optimize the number of calls and reduce the number of errors in the whole process.
This article explains practices by some big cloud services:
http://blog.cloud-elements.com/oauth-2-0-access-refresh-token-guide
However, IMO, the refresh token should have an expiration time, say 1 year. It should change when a new access token is issued using the refresh token, however, the expiry date should remains the same. When you need a refresh token forever, just issue the refresh token with max date value. Also, make sure to mark the old access and refresh tokens as deleted when issuing the new refresh token.