amazon-archives / amazon-cognito-auth-js

The Amazon Cognito Auth SDK for JavaScript simplifies adding sign-up, sign-in with user profile functionality to web apps.
Apache License 2.0
423 stars 232 forks source link

Do we need to manually refresh the Id token and Access token with refresh token? #154

Open clin9 opened 6 years ago

clin9 commented 6 years ago

I'm not sure if there is method to automatically refresh the Id token and Access token when they are expired? Or we are able to use getCacheSession or getSession directly to refresh them.

chamathsilva commented 6 years ago

Yes, you have to do it manually once token expired (after 1 hour ). You can do it via refreshSession() method.

let user = auth.getCachedSession(); auth.refreshSession(user.getRefreshToken().getToken())

YoniH commented 5 years ago

It seems that getSession() does that for you:

    /**
     * This is used to get a session, either from the session object
     * or from the local storage, or by using a refresh token
     * @param {string} RedirectUriSignIn Required: The redirect Uri,
     * which will be launched after authentication.
     * @param {array} TokenScopesArray Required: The token scopes, it is an
     * array of strings specifying all scopes for the tokens.
     * @returns {void}
     */
    getSession() {
      const tokenScopesInputSet = new Set(this.TokenScopesArray);
      const cachedScopesSet = new Set(this.signInUserSession.tokenScopes.getScopes());
      const URL = this.getFQDNSignIn();
      if (this.signInUserSession != null && this.signInUserSession.isValid()) {
        return this.userhandler.onSuccess(this.signInUserSession);
      }
      this.signInUserSession = this.getCachedSession();
      // compare scopes
      if (!this.compareSets(tokenScopesInputSet, cachedScopesSet)) {
        const tokenScopes = new CognitoTokenScopes(this.TokenScopesArray);
        const idToken = new CognitoIdToken();
        const accessToken = new CognitoAccessToken();
        const refreshToken = new CognitoRefreshToken();
        this.signInUserSession.setTokenScopes(tokenScopes);
        this.signInUserSession.setIdToken(idToken);
        this.signInUserSession.setAccessToken(accessToken);
        this.signInUserSession.setRefreshToken(refreshToken);
        this.launchUri(URL);
      } else if (this.signInUserSession.isValid()) {
        return this.userhandler.onSuccess(this.signInUserSession);
      } else if (!this.signInUserSession.getRefreshToken()
      || !this.signInUserSession.getRefreshToken().getToken()) {
        this.launchUri(URL);
      } else {
        this.refreshSession(this.signInUserSession.getRefreshToken().getToken());
      }
      return undefined;
    }
bala1074 commented 5 years ago

how to handle same situationat nodejs backend? please share if any resource or poc available on Cognito nodejs backend