OAuth Refresh Token Best Practice

23,022

Solution 1

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.

Solution 2

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.

Share:
23,022
Angel Gao
Author by

Angel Gao

CS student @ UW.

Updated on August 19, 2020

Comments

  • Angel Gao
    Angel Gao over 3 years

    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:

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

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