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
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.