Search code examples
androidoauth-2.0jwtaccess-tokensystemtime

Refresh access token before it expires using refresh token


I am working on an application, which uses OAuth - Token based authentication.

This is how the flow looks like, considering we have the access and refresh token.

  1. Api call -> intercepter appends access-token -> api returns 200
  2. Api call -> intercepter appends expired access-token -> api returns 401 -> intercepter refreshes token using refresh token -> interceptor retries same req -> returns 200
  3. Api call -> intercepter appends expired access-token -> api returns 401 -> intercepter refreshes token using refresh token(refresh token is also expired) -> prompt guest to sign-in -> guest signed-in -> retry request

This all works great and fine - I am considering to optimise it a bit i.e i don't want to call api and wait for 401 to return. Instead check for token expiration beforehand, get the new access token and then call the api with valid token.

This approach of calculating the expiry of token using android system time might work - but can be misused sometimes when user changes the android time.

Wondering if there a better solution to avoid the expiry issue of time based on android system time.


Solution

  • Even if you add such a check in your code, you will still need that flow you presented in the question (so catching 401s and refreshing tokens accordingly). This is because, as you noticed, time settings on the client device can be changed, or there might be a slight clock skew between the client and the server (so no intentional tampering with time settings).

    The approach where you check for expiry before the API call will work only if you have access to the expiration time of the access and refresh tokens. So either you received that information together with tokens and persisted it, or JWTs are used and you can easily check expiration.

    Personally, I wouldn't add such a check unless there is some strong argument for it (e.g. you know that your app will be mainly used in remote locations with slow connections and you want to limit traffic to a minimum, etc.). The flow that you presented is a common one and works just fine.