Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remember & autorefresh login token when using Amazon Web Services Cognito Userpool?

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?

like image 836
Duke Dougal Avatar asked Feb 02 '17 13:02

Duke Dougal


People also ask

What is the secret to memorize?

To memorize something quickly, repeat the information right after learning it. The second repetition should be after 15 to 20 minutes. You don't need to return to the information between repetitions. Instead, just rest and do something different to let your brain relax.


1 Answers

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
    });
}
like image 78
Ionut Trestian Avatar answered Nov 10 '22 18:11

Ionut Trestian