javascriptamazon-web-servicesamazon-cognito

AWS Cognito - Invalid Refresh Token


I am using the Amazon Cognito service with the amazon-cognito-identity-js library, and am having an issue refreshing a user's tokens, namely the id token.

When trying to refresh the users tokens by making an unauthenticated initiateAuth request, I receive a 400 http status in response, along with an "Invalid Refresh Token" error message.

POST https://cognito-idp.us-east-1.amazonaws.com/ 400 (Bad Request)

Uncaught Error: Invalid Refresh Token.

Why does it believe that I am passing in invalid refresh token?

// the refresh token
var reToken;

// pool config
var poolData = {
    UserPoolId : 'us-east-1_XXXXXXXXX',
    ClientId : 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
};

// connect to user pool and 
// find the current user
var CognitoUserPool = AmazonCognitoIdentity.CognitoUserPool;
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();

// if we found a user
if (cognitoUser != null)
{
    // get active user session
    cognitoUser.getSession(function(err, session)
    {
        // catch errors
        if (err) {
            alert(err);
            return;
        }

        // get the refresh token
        reToken = session.refreshToken.token;
    });
}

// get current epoch time
var curDate = new Date();
var currentEpoch = Math.round(curDate.getTime() / 1000);

// get the epoch when the token
// was last issued
var issuedEpoch = store.get('issued');

// set the refresh parameters
var refreshParams = {
    ClientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXX',
    AuthFlow: 'REFRESH_TOKEN_AUTH',
    AuthParameters: { 'REFRESH_TOKEN': reToken }
};

// note: 30 minutes = 1800 seconds
// if a token was last issued over 30 minutes ago
if ( (currentEpoch - issuedEpoch) >= 1800 )
{
    // refresh the users token with a new token
    userPool.client.makeUnauthenticatedRequest('initiateAuth', refreshParams, (err, newToken) => {
        // catch errors
        if (err) {
            alert(err);
            return;
        }

        // do stuff with the returned token
        console.log(newToken)
    })

}

As an aside, i've tried using refreshSession() but it tells me that getToken() is not a function of refreshSession().

cognitoUser.refreshSession(reToken, (err, authResult) => {
    if (err) throw err;
    console.log(authResult)
});

Solution

  • I've found the answer.

    As it turns out, it wasn't really an invalid refresh token; at least in the sense of the object itself.

    If you have device tracking enabled, then you must pass the users device key in the AuthParameters (which I wasn't doing).

    I read through the description of device tracking, as found here, and it didn't seem applicable for my use-case so I simply turned it off (User Pool > Sign-in > Device tracking).

    The above code worked after that.