2

I have an api that returns this after authentication

"token_type":"Bearer",
"expires_in":86400,
"access_token":"XXXXXXXXX",
"refresh_token":"XXXXXXXXXXX"

I have successfully saved the access token, refresh token and the expires_in in an sqlite database. How can i check if the token has expired ? Here is what i have so far

if(new Date().after(expiresAt)){
            Toast.makeText(this, "Token expired", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "You still have time", Toast.LENGTH_SHORT).show();
        }

expiresAt contains the expires_in value

George J
  • 195
  • 1
  • 4
  • 20

1 Answers1

7

I would suggest you to use framework such as retrofit to help you manage the authentication without checking the expiresAt in every single API call.

In Retrofit, or its HTTP client OkHttp. You can handle authentication by using new Authenticator API, designed specifically for your refresh token/auto login scenario. You may refer to this link for implementation details refreshing-oauth-token-using-retrofit-without-modifying-all-calls

Whenever your API call return a "401 unauthorized" respond, it will trigger authenticator method, run your refresh token API and resend the original request with new access token.

Community
  • 1
  • 1
Fernando Tan
  • 634
  • 4
  • 14