2
votes

I'm working with an API that uses OAuth2, provides an access token that expires in 3600 seconds, and provides a refresh token with it. Originally, I'd waited for an API call to fail in a way that indicated the access token was expired and then tried to refresh the access token using the refresh token. This has become problematic when the access token is expired and several API calls are made concurrently (each call separately triggers a refresh and most of the calls fail).

Would it be better to automatically refresh the access token using the refresh token after 3600 seconds? (Or 3599 seconds or 3601 seconds?) Is there a different paradigm I should be using for refreshing the access token?

2

2 Answers

1
votes

Ideally, the client should have sufficient smarts to not use an expired access token. Fortunately the response from your OAuth AS's token endpoint should include the expires_in attribute to confirm that the expiry will be in 3600 seconds. E.g.:

{"token_type":"Bearer","expires_in":3600,"refresh_token":"p8BPdo01kkjh6fhatclD3wwBEQblm4kL4ctYRVlrHo","access_token":"9XebAAXeu6hQOAiwmOk8vdhRyUFV"}

Since this JSON response is generated by the server, there's a chance that the transmission back to the client has taken time, and thus the "expires_in" value may be smaller than it appears.

Given that, I'd recommend that you have some sort of buffer (say 5-10 seconds) before expiry to automatically use your refresh token to request a new access token.

0
votes

I may have used the following scenario. There will be access failures due to access token validation error but those errors will be minimal.

  1. App1 invokes the token api with password grant type and get the access token and refresh token pair (accto1/refto1)
  2. App2 also do the same at the starting up of the execution (accto1/refto1)
  3. When the access token is expired for App1, he may do the refresh token by invoking the token api with refresh token grant type and with his existing refresh token (refto1) and he will retrieve a new pair of access token and refresh token. (accto2/refto2)
  4. When App2 also reaches the instance when his access token is expired, he will also try the refresh token grant with the refresh token he already has (refto1) but he will get an authorization error since that refresh token is now expired.

  5. When either of the apps get this error then app needs to realize that someone else has refreshed the token so at this moment the app needs to make a call with the password grant to retrieve the new access token / refresh token pair in action. This time as in the example the App2 will also retrieve the same access token and refresh token pair that the App1 has previously received for his refresh token grant. (accto2/refto2)