how handle refresh token service in AWS amplify-js

前端 未结 5 1505
终归单人心
终归单人心 2021-01-03 16:14

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

5条回答
  •  灰色年华
    2021-01-03 16:37

    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
              }
          }); 
        })
    }
    

提交回复
热议问题