21
votes

I am developing an application that uses AWS Cognito as the Identity Provider. So the user authenticate on AWS Cognito Pool and get the Access Token, Access ID and Refresh token. Then the user can make backend requests to my app. I get the Access Token validate it, get the user profile on Cognito AWS and authorize the request.

The problem is that after the Access token has expired, and the client send the expired token to the backend, the backend app get an error (token experied or not authorized).

How can I make this workflow works?

I was thinking in send to the client a message that the token has expired, and the the cliente refresh it against the Cognito Pool. Is it the correct approach?

3

3 Answers

28
votes

When you get the Access Token, ID and Refresh token from Cognito User Pools, you must cache it locally. The Access and the ID token are valid for 1 hour and should be reused as much as possible within that time period.

These tokens are JWT tokens and hold the expiry time within themselves. You can decode the JWT token and also cache this expiry along with the token. Every time the cache for the tokens is accessed, also check the current time against the cached expiry time. If expired, use the Refresh token to obtain the latest Access and ID token and cache the tokens and expiry again.

If you use one of our high level SDKs for Android, iOS of JavaScript, the SDK manages all of this for you.

3
votes

you can find more information How-to use them on this link.http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html.

To use the refresh token to get new tokens, use the AdminInitiateAuth API, passing REFRESH_TOKEN_AUTH for theAuthFlow parameter and the refresh token for the AuthParametersparameter with key "REFRESH_TOKEN". This initiates the token refresh process with the Amazon Cognito server and returns new ID and access tokens.

In short, call the AdminInitiateAuth action with the refresh token. Take a look at the SDK of your development language you prefer.

2
votes

In my projects I use AWS Amplify library and I found this approach to work:

Configuration:

import Amplify, { Auth } from "aws-amplify";

Amplify.configure({
  Auth: {
    userPoolId: <USER_POOL_ID>,
    userPoolWebClientId: <USER_POOL_WEB_CLIENT_ID>
  }
});

Refresh tokens

try {
    const currentUser = await Auth.currentAuthenticatedUser();
    const currentSession = currentUser.signInUserSession;
    currentUser.refreshSession(currentSession.refreshToken, (err, session) => {
      // do something with the new session
    });
  } catch (e) {
    // whatever
  }
};

More discussion here: https://github.com/aws-amplify/amplify-js/issues/2560.