curchod
curchod

Reputation: 291

What is the best way to refresh an AWS Cognito session in an Angular app

I am using AWS Cognito to authenticate users for an app. I want to refresh the session automatically every hour without the user having to log in again. My current solution is to save the time since last login and check that against the current time to decide when to call cognito user pool refreshSession function from the amazon-cognito-identity-js library.

The question I have is if this is the best way to do this. Is it a best practice to save the time of login?

Upon login, the cognito user session id token payload has these properties:

auth_time: 1565305136
exp: 1565308736
iat: 1565305137

I can't find any info on what those values represent or if they could be used to check the current session expiration time. There is also an cognitoUser.getSession.isValid function which relies on a Cognito callback that would work also. I would rather not use this approach as I need to set the access token in the header for each request, which is currently done in an Angular interceptor class. Using an async callback in every request seems like a bad idea when we can check the time ourselves after storing it in local storage.

Another question is if there is an Amplify way of doing this. My understanding is that Amplify which includes CLI functions an also uses amazon-cognito-identity-js under the hood. However, we have not used Amplify. Our implementation is based on the demonstration Angular Cognito app here.

However, there may be a more current way to do this, for example by just setting some kind of flag with Amplify.

Any help to clarify a best practice for automatic Cognito session refreshing would be much appreciated.

Upvotes: 2

Views: 2259

Answers (1)

Saiful Azad
Saiful Azad

Reputation: 1921

Sharing our approach to you which is working fine at some angular projects.

  • At cognito side set refresh token expiration 365 days for aws cognito client settings.
  • At angular, in AppComponent(entry point) try to authenticate by existing refresh token. If no refresh token at localstorage or failed to auth by existing refresh token go to login page. Also in AppComponentadd an interval that will emit every 30 minutes interval after app loads. That will work as a cron job, will call cognito API for new token by localstorage refresh token. So every 30 minutes after app loads new token will be saved at localstorage.

export class AppComponent {
  ngOnInit() {
    const s = interval(interval_in_mili_sec);
    s.subscribe(value => {
      // call id token API
    });
  }
  
}

Hope this will help you.

Upvotes: 2

Related Questions