Search code examples
javascriptamazon-web-servicesamazon-cognitoaws-sdk-js

Problem refreshing the AWS Cognito ID Token


I'm trying to refresh the AWS Cognito ID Token using the AWS SDK for javascript. We need the token ID to be refreshed automatically without any action with our users. I create the following function and we will check the expiration time that is fetched after authentication and when the current time is near expiration time, we will call this function.

refreshToken(success, failure) {
    var poolData = {
        UserPoolId: this.initializeData.UserPoolId,
        ClientId: this.initializeData.ClientId,
    };
    var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
    var cognitoUser = userPool.getCurrentUser();

    cognitoUser.getSession(function (err, session) {
        if (err) {
            alert(err.message || JSON.stringify(err));
            return;
        }

        AWS.config.region = 'us-east-2';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: 'myIdentityPoolId',
            Logins: {
                'cognito-idp.us-east-2.amazonaws.com/myPoolId': session.getIdToken().getJwtToken(),
            },
        });

        AWS.config.credentials.refresh(error => {
            if (error) {
                console.error(error);
            } else {
                var refresh_token = session.getRefreshToken();
                console.log('refresh started.');
                
                cognitoUser.refreshSession(refresh_token, (err, session) => {
                    if (err) {
                        console.log(err);
                    } else {
                        AWS.config.credentials.params.Logins[
                            'cognito-idp.us-east-2.amazonaws.com/myPoolId'
                        ] = session.getIdToken().getJwtToken();
                        AWS.config.Credentials.refresh(err => {
                            if (err) {
                                console.log(err);
                            } else {
                                console.log('TOKEN SUCCESSFULLY UPDATED');
                                console.log(cognitoUser.getSession().getJWTToken);
                            }
                        });
                    }
                });
            }
        });
    });
}

But I received the following error in my console.

TypeError: AWS.config.Credentials is undefined
on the following line:
AWS.config.Credentials.refresh(err => {
what should I do to solve the problem?


Solution

  • The problem is solved by using the following statement instead of using AWS.config.Credentials.refresh:

    ( < AWS.CognitoIdentityCredentials > myAwsConfig.credentials).refresh();
    

    Here is the completed code that works and it refreshes the token ID of the AWS Cognito User:

      refreshToken(success, failure) {
        var poolData = {
          UserPoolId: this.initializeData.UserPoolId,
          ClientId: this.initializeData.ClientId,
        };
        var userPool = new CognitoUserPool(poolData);
        var cognitoUser = userPool.getCurrentUser();
        var currentSession = null;
    
        cognitoUser.getSession(function (err, session) {
          if (err) {
            alert(err.message || JSON.stringify(err));
            return;
          }
          currentSession = session;
        });
    
        if(!currentSession){
          failure("there is a problem with current session. try again later.");
        }
    
        AWS.config.region = 'us-east-2';
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: this.initializeData.IdentityPoolId,
            Logins: {
                'cognito-idp.us-east-2.amazonaws.com/poolId': currentSession.getIdToken().getJwtToken(),
            },
        });
    
        var refresh_token = currentSession.getRefreshToken(); 
          cognitoUser.refreshSession(refresh_token, (err, session) => {
    
            if (err) {
              failure(err);
            } else {
    
              var myAwsConfig = AWS.config;
              myAwsConfig.credentials.sessionToken = session.getIdToken().getJwtToken();
    
              ( < AWS.CognitoIdentityCredentials > myAwsConfig.credentials).refresh(err => {
                if (err) {
                  failure(err);
                } else {
                  success(session.getIdToken().getJwtToken());
                }
              });
            }
          });
      }