Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how handle refresh token service in AWS amplify-js

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.

like image 943
techie18 Avatar asked Nov 19 '18 13:11

techie18


People also ask

How do I use Amplify to refresh token?

If you are using Amazon Cognito via Amplify JS and if you need to refresh tokens, then all you need to do is following: import { Auth } from 'aws-amplify'; Auth. currentSession() . then(data => console.

How do you handle a refresh JWT token?

We'll first create an express app and then implement two routes login & refresh. The login route will get a post request, then it will check the credentials if they match it'll send a refresh token and access token in response.

How do you handle refresh token?

To use the refresh token, make a POST request to the service's token endpoint with grant_type=refresh_token , and include the refresh token as well as the client credentials if required.

How do you refresh a Cognito ID token?

Initiate new refresh tokens (API)Pass REFRESH_TOKEN_AUTH for the AuthFlow parameter. The authorization parameter, AuthParameters , is a key-value map where the key is "REFRESH_TOKEN" and the value is the actual refresh token. Amazon Cognito returns new ID and access tokens after your API request passes all challenges.


2 Answers

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:

const getAccessJwtToken = async () => {
  // Auth.currentSession() checks if token is expired and refreshes with Cognito if needed automatically
  const session = await Auth.currentSession();
  return session.getAccessToken().getJwtToken();
};

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.

like image 133
sc00ter Avatar answered Sep 23 '22 02:09

sc00ter


After a long struggle, I found the solution to update the AWS Cognito refresh token, To do this I am using the amazon-cognito-identity-js

const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;

componentWillReceiveProps(nextProps) {
let getIdToken = localStorage.getItem('idToken');
    if(getIdToken !== null){
      let newDateTime = new Date().getTime()/1000;
      const newTime = Math.trunc(newDateTime);
      const splitToken = getIdToken.split(".");
      const decodeToken = atob(splitToken[1]);
      const tokenObj = JSON.parse(decodeToken);
      const newTimeMin = ((newTime) + (5 * 60)); //adding 5min faster from current time
      //console.log(newTimeMin, tokenObj.exp)
      if(newTimeMin > tokenObj.exp){
          this.tokenRefresh();
          console.log('token updated');
      }
    }
}

Updating the token method

tokenRefresh(){
    const poolData = {
      UserPoolId : // Your user pool id here,
      ClientId : // Your client id here
    };
    const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
    const cognitoUser = userPool.getCurrentUser();
    cognitoUser.getSession((err, session) =>{
      const refresh_token = session.getRefreshToken();
      cognitoUser.refreshSession(refresh_token, (refErr, refSession) => {
          if (refErr) {
              throw refErr;
          }
          else{
              //this provide new accessToken, IdToken, refreshToken
              // you can add you code here once you get new accessToken, IdToken, refreshToken
          }
      }); 
    })
}
like image 29
techie18 Avatar answered Sep 22 '22 02:09

techie18