Cognito User Pool: How to refresh Access Token using Refresh Token

Amazon Web-ServicesAws LambdaAmazon Cognito

Amazon Web-Services Problem Overview


I am using Cognito user pool to authenticate users in my system. A successful authentication gives an ID Token (JWT), Access Token (JWT) and a Refresh Token. The documentation here, clearly mentions that the refresh token can be used to refresh access token, but does not mention how. My question is once my Access Token expires, how do I use the stored refresh token to refresh my access token again?

I searched through the JavaScript SDK and could not find any method to do the same. I definitely missed something.

Also I was thinking to do this via a Lambda function which takes in the access token and refresh token and responds with a refreshed access token. Would be great if anyone can throw some light on this.

Amazon Web-Services Solutions


Solution 1 - Amazon Web-Services

If you're in a situation where the Cognito Javascript SDK isn't going to work for your purposes, you can still see how it handles the refresh process in the SDK source:

You can see in refreshSession that the Cognito InitiateAuth endpoint is called with REFRESH_TOKEN_AUTH set for the AuthFlow value, and an object passed in as the AuthParameters value.

That object will need to be configured to suit the needs of your User Pool. Specifically, you may have to pass in your SECRET_HASH if your targeted App client id has an associated App client secret. User Pool Client Apps created for use with the Javascript SDK currently can't contain a client secret, and thus a SECRET_HASH isn't required to connect with them.

Another caveat that might throw you for a loop is if your User Pool is set to remember devices, and you don't pass in the DEVICE_KEY along with your REFRESH_TOKEN. The Cognito API currently returns an "Invalid Refresh Token" error if you are passing in the RefreshToken without also passing in your DeviceKey. This error is returned even if you are passing in a valid RefreshToken. The thread linked above illuminates that, though I do hope AWS updates their error handling to be less cryptic in the future.

As discussed in that thread, if you are using AdminInitiateAuth along with ADMIN_NO_SRP_AUTH, your successful authentication response payload does not currently contain NewDeviceMetadata; which means you won't have any DeviceKey to pass in as you attempt to refresh your tokens.

My app calls for implementation in Python, so here's an example that worked for me:

def refresh_token(self, username, refresh_token):
    try:
        return client.initiate_auth(
            ClientId=self.client_id,
            AuthFlow='REFRESH_TOKEN_AUTH',
            AuthParameters={
                'REFRESH_TOKEN': refresh_token,
                'SECRET_HASH': self.get_secret_hash(username)
                # Note that SECRET_HASH is missing from JSDK
                # Note also that DEVICE_KEY is missing from my example
            }
        )
    except botocore.exceptions.ClientError as e:
        return e.response

Solution 2 - Amazon Web-Services

The JavaScript SDK handles refreshing of the tokens internally. When you call getSession to get tokens, in the absence of any valid cached access and id tokens the SDK uses the refresh token to get new access and id tokens. It invokes the user authentication, requiring user to provide username and password, only when the refresh token is also expired.

Solution 3 - Amazon Web-Services

Refreshing a session with the amazon-cognito-identity-js browser SDK; it mostly does it for you, and unless you're doing something unusual you won't need to handle the refresh token directly. Here's what you need to know:

Assume you have instantiated the user pool like this:

const userPool = new AmazonCognitoIdentity.CognitoUserPool({
  UserPoolId: USER_POOL_ID,
  ClientId: USER_POOL_CLIENT_ID
});

To find the last username authenticated, you would do this:

const cognitoUser = cognitoUserPool.getCurrentUser();

If it finds one, cognitoUser will be non-null, and you can do this, which will refresh your tokens behind the scenes if needed:

cognitoUser.getSession(function(err, data) {
  if (err) {
    // Prompt the user to reauthenticate by hand...
  } else {
    const cognitoUserSession = data;
    const yourIdToken = cognitoUserSession.getIdToken().jwtToken;
    const yourAccessToken = cognitoUserSession.getAccessToken().jwtToken;
  }
});

If you don't want these tokens persisted in local storage, you can:

cognitoUser.signOut();

The way it works is, after a successful authentication, the browser will store your JWT tokens, including that refresh token. It stores these in local storage in your browser by default, though you can provide your own storage object if you want. By default, the refresh token is valid for 30d, but it's a property (RefreshTokenValidity) of your UserPoolClient, which you can change. When you do the above, getSession() will first see whether the tokens you have in storage exist and are still valid; if not, it will try to use whatever refreshToken it finds there to authenticate you into a new session.

The documentation http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html indicates that the iOS and Android SDKs will do this for you, though I have not used those so can't vouch for that.

Solution 4 - Amazon Web-Services

I've been struggling with this as well in Javascript. Here's my solution, it is based on https://github.com/aws/amazon-cognito-identity-js BUT it doesn't rely on storage so you can use it in a lambda function if you wish. Edit: Fixed code, thanks to Crayons

const userPool = new AWSCognito.CognitoUserPool({
  UserPoolId: <COGNITO_USER_POOL>,
  ClientId: <COGNITO_APP_ID>
})

userPool.client.makeUnauthenticatedRequest('initiateAuth', {
  ClientId: <COGNITO_APP_ID>,
  AuthFlow: 'REFRESH_TOKEN_AUTH',
  AuthParameters: {
    'REFRESH_TOKEN': <REFRESH_TOKEN> // client refresh JWT
  }
}, (err, authResult) => {
  if (err) {
     throw err
  }
  console.log(authResult) // contains new session
})

Solution 5 - Amazon Web-Services

If you have a refresh token then you can get new access and id tokens by just making this simple POST request to Cognito:

POST https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token >
Content-Type='application/x-www-form-urlencoded'
Authorization=Basic base64(client_id + ':' + client_secret)

grant_type=refresh_token&
client_id=YOUR_CLIENT_ID&
refresh_token=YOUR_REFRESH_TOKEN

You will get the following response back:

HTTP/1.1 200 OK
Content-Type: application/json

{
   "access_token":"eyJz9sdfsdfsdfsd", 
   "id_token":"dmcxd329ujdmkemkd349r",
   "token_type":"Bearer", 
   "expires_in":3600
}

Keep in mind the Authorization header should contain the computed base64 aforementioned.

Solution 6 - Amazon Web-Services

Here is an example of how to do it with JavaScript on the server side using Node.js.

const AccessToken = new CognitoAccessToken({ AccessToken: tokens.accessToken });
const IdToken = new CognitoIdToken({ IdToken: tokens.idToken });
const RefreshToken = new CognitoRefreshToken({ RefreshToken: tokens.refreshToken });

const sessionData = {
  IdToken: IdToken,
  AccessToken: AccessToken,
  RefreshToken: RefreshToken
};
const userSession = new CognitoUserSession(sessionData);

const userData = {
  Username: email,
  Pool: this.userPool
};

const cognitoUser = new CognitoUser(userData);
cognitoUser.setSignInUserSession(userSession);

cognitoUser.getSession(function (err, session) { // You must run this to verify that session (internally)
  if (session.isValid()) {
    // Update attributes or whatever else you want to do
  } else {
    // TODO: What to do if session is invalid?
  }
});

You can see a complete working example in my blog post How to authenticate users with Tokens using Cognito.

Solution 7 - Amazon Web-Services

Using NodeJS aws-sdk and a bit of Promise you can await authentication using Refresh Token with initiateAuth as follows:

const {CognitoIdentityServiceProvider} = require('aws-sdk');

const initiateAuth = (ClientId, REFRESH_TOKEN, DEVICE_KEY) =>
    new Promise((resolve, reject) => {
        const CISP = new CognitoIdentityServiceProvider();

        CISP.initiateAuth(
            {
                ClientId, // Cognito App Client Id
                AuthFlow: 'REFRESH_TOKEN_AUTH',
                AuthParameters: {
                    REFRESH_TOKEN,
                    DEVICE_KEY
                }
            },
            (err, data) => {
                if (err) {
                    return reject(err);
                }

                resolve(data);
            }
        );
    });

// ------ Usage ------ //

(async () => {
    const tokens = await initiateAuth('mY4pps3cR3T', '<R3FR3SHT0K3N>');

    console.log('Tokens', tokens);

    const {AuthenticationResult: {AccessToken, IdToken, ExpiresIn, TokenType}} = tokens;
})()

> Keep in mind that if Device tracking is enabled you should pass a device key otherwise you can receive Invalid refresh token error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHardik ShahView Question on Stackoverflow
Solution 1 - Amazon Web-ServicesafilbertView Answer on Stackoverflow
Solution 2 - Amazon Web-ServicesM ReddyView Answer on Stackoverflow
Solution 3 - Amazon Web-ServicespisomojadoView Answer on Stackoverflow
Solution 4 - Amazon Web-ServicesGrumpyOldManView Answer on Stackoverflow
Solution 5 - Amazon Web-ServicesGautam JainView Answer on Stackoverflow
Solution 6 - Amazon Web-ServicesRickView Answer on Stackoverflow
Solution 7 - Amazon Web-ServicesPaul T. RawkeenView Answer on Stackoverflow