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

56,603

Solution 1

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

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

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

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

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.

Share:
56,603
Hardik Shah
Author by

Hardik Shah

Updated on June 19, 2021

Comments

  • Hardik Shah
    Hardik Shah almost 3 years

    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.

  • Sam Hosseini
    Sam Hosseini over 7 years
    Thank you very much @afilbert for the informative post. I was not passing in DEVICE_KEY and I was getting 'Invalid Refresh Token' error, which is a very bad error handling on AWS side.
  • SexxLuthor
    SexxLuthor about 7 years
    Nice answer, @afilbert--upvoted. (Unfortunately SO users started treating upvotes like personal spending money a few years ago. ;)
  • Dynite
    Dynite almost 7 years
    Thank you so much for the pointer about the device key! (I disabled device tracking and it works fine again).
  • Deep Kakkar
    Deep Kakkar almost 7 years
    Mahesh, can you please give the code example there?
  • nu everest
    nu everest almost 7 years
    @afilbert Is SECRET_HASH the same thing as App client secret? Nevermind, the answer is "Yes" docs.aws.amazon.com/cognito-user-identity-pools/latest/…
  • afilbert
    afilbert almost 7 years
    @nueverest the SECRET_HASH is required if the User Pool App has been defined with an App client secret, but they are not the same thing. The boto3 docs describe the SecretHash as the following: "A keyed-hash message authentication code (HMAC) calculated using the secret key of a user pool client and username plus the client ID in the message." boto3.readthedocs.io/en/latest/reference/services/… If you post a question on SO about how to create the SECRET_HASH, I'd be more than happy to share my solution as an answer.
  • nu everest
    nu everest almost 7 years
    @afilbert New question posted here: stackoverflow.com/questions/44244441/…
  • Clive Sargeant
    Clive Sargeant almost 7 years
    hi Mahesh (and others that may need this) see link here github.com/aws/amazon-cognito-identity-js specifically use case 16. The returned session contains the tokens.
  • Luiz Henrique Martins Lins Rol
    Luiz Henrique Martins Lins Rol almost 7 years
    Has anyone faced an issue where. upon trying to refresh the token using the initiateAuth, a "Invalid login token. Token expired: 1502028294 >= 1502027330" occurs?
  • Crayons
    Crayons over 6 years
    This works, however, AuthParameters format should be "REFRESH_TOKEN": <your_refresh_token>. Also note that if you have device tracking enabled, you must pass the clients device key in AuthParameters or turn device tracking off.
  • ecoe
    ecoe almost 6 years
    the headers aren't shown, but as of Jun 2018, they should be: Content-Type:application/x-amz-json-1.0 X-AMZ-TARGET:com.amazonaws.cognito.identity.idp.model.AWSCog‌​nitoIdentityProvider‌​Service.InitiateAuth
  • BLang
    BLang almost 5 years
    In this link, check the, "Get current user" section of their docs. When you call cognitoUser.getSession() the sdk will refresh your access/ ID tokens for you automatically, good to do before calling authenticated routes in your APIs. docs.aws.amazon.com/cognito/latest/developerguide/…
  • GBP
    GBP over 4 years
    Thanks Mahesh. Anyone looking for the confirmation on the above comment, please visit github.com/aws-amplify/amplify-js/blob/master/packages/…
  • George Hernandez
    George Hernandez about 4 years
    This would have been a concise solution if it did return a refresh_token, but it does not. The example you give comes from the AWS documentation (docs.aws.amazon.com/cognito/latest/developerguide/…) but they also offer a note: The refresh token is defined in the specification, but is not currently implemented to be returned from the Token Endpoint.
  • pincopallino
    pincopallino over 3 years
    FYI in order to be able to call REFRESH_TOKEN_AUTH after an ADMIN_NO_SRP_AUTH, you have to disable the device tracking. This was not very clear, hope it helps anybody!
  • Fx.
    Fx. about 3 years
    Thinks have changed :) The token endpoint returns refresh_token only when the grant_type is authorization_code.
  • jweyrich
    jweyrich almost 3 years
    This answer is correct! I updated the HTTP response to reflect the fact that it doesn't return a new refresh token. Refreshing a token only gives you a new access token and a new id token. The refresh token used to renew them is valid for 30 days by default - if you didn't change it. And the refresh token itself cannot be renewed, but you can increase its validity up to 10 years (not something I'd recommend though).
  • Brayden G
    Brayden G about 2 years
    This solved hours of work trying to figure out how to use a IdentityPoolId to refresh a token with the amazon-cognito-identity-js library just to find out that all we had to do was call getSession and the identity pool id was not need! Thank you so much, I was trying user pool id's and other stuff and this fixed everything.