Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OAuth Refresh Token Best Practice [closed]

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.

like image 637
Angel Gao Avatar asked Mar 20 '15 15:03

Angel Gao


People also ask

When should a refresh token expire?

The refresh token is set with a very long expiration time of 200 days. If the traffic to this API is 10 requests/second, then it can generate as many as 864,000 tokens in a day.

When should I use OAuth refresh token?

The Refresh Token grant type is used by clients to exchange a refresh token for an access token when the access token has expired. This allows clients to continue to have a valid access token without further interaction with the user.

Should you store refresh token?

The client needs to store the refresh token safely. A malicious attacker gets access to the refresh and access token and uses it to request protected data to the resource server. The malicious attacker can get protected data from the resource server.

How do I protect my refresh token?

Protecting your refresh tokens Concretely, refresh tokens exposed to the browser should be protected with Refresh Token Rotation (RTR). In a nutshell, RTR makes refresh tokens only valid for one-time use. Each time a refresh token is used, the security token service issues a new access token and a new refresh token.


1 Answers

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.

like image 140
Hans Z. Avatar answered Sep 20 '22 05:09

Hans Z.