6

I have built a website that uses AWS Cognito with the Userpool functionality.

If I leave the page, the login is forgotten, and after one hour the token expires.

I'd like the login to be remembered when the user closes their browser and comes back.

I'd also like the auth token to auto refresh instead of just giving errors after one hour.

How can I do this?

Duke Dougal
  • 24,359
  • 31
  • 91
  • 123

2 Answers2

6

The user pool tokens are saved to local storage. And when calling getCurrentUser on a user pool object you can retrieve the last authenticated user object. After that, calling getSession should use the refresh token to retrieve new access tokens if they are expired such as in the example below. In the callback for getSession, you should have a valid session.

var poolData = {
    UserPoolId : '...', // Your user pool id here
    ClientId : '...' // Your client id here
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();

if (cognitoUser != null) {
    cognitoUser.getSession(function(err, session) {
        if (err) {
           alert(err);
            return;
        }
        console.log('session validity: ' + session.isValid());
        //You should have a valid session here
    });
}
lionels
  • 782
  • 7
  • 12
Ionut Trestian
  • 5,473
  • 2
  • 20
  • 29
  • Is it necessary to do AWS.config.credentials.refresh after the getSession? – Duke Dougal Feb 15 '17 at 21:11
  • 2
    If you're using Cognito Identity to get AWS credentials to access other AWS services and you are setting the Logins map for that, you would have to call refresh or get to actually retrieve the new credentials. If you're not actually using Cognito Identity then not. – Ionut Trestian Feb 15 '17 at 21:21
  • 1
    @IonutTrestian is it possible for you to mention, how to do the refreshing? – Kulasangar Mar 08 '18 at 06:14
0

For how to remember user, and not have to re-login after page reload, see answer here: https://stackoverflow.com/a/70383024/284651

For refreshing the token, see documentation & example code in the docs here: https://docs.amplify.aws/lib/auth/advanced/q/platform/js/#token-refresh

There is also some relevant discussion here: https://github.com/amazon-archives/amazon-cognito-identity-js/issues/271

spdrman
  • 1,372
  • 2
  • 13
  • 18