how handle refresh token service in AWS amplify-js

Question:

In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession() I will call this for every 1 hour but it’s not working for me.

Answer:

Calling Auth.currentSession() should solve your problem. Amplify-js abstracts the refresh logic away from you.

Under the hood currentSession() gets the CognitoUser object, and invokes its class method called getSession(). It’s this method, that does the following:

  1. Get idToken, accessToken, refreshToken, and clockDrift from your storage.
  2. Validate the tokens (i.e. idToken, and accessToken) to see if they have expired or not.
  3. If tokens are valid, return current session.
  4. If tokens are expired, invoke the refreshSession() method of the CognitoUser class, which communicates to the AWS Identity Provider to generate a new set of tokens.

All you have to do now is either:

  1. Make sure to call Auth.currentSession() at regular intervals
  2. Always call Auth.currentSession() to get your token for each http request that you make.

You could use a wrapper like this:

Lastly, this github discussion also introduces a very good manual way to refresh your token and introduces a use case for when you should explore that option.

Leave a Reply