user9361329
user9361329

Reputation:

how handle refresh token service in AWS amplify-js

In my react project I am using AWS Cognito user pool for user management, for user authentication, I am using AWS Cognito idToken. after 90min the session will expire, then I need to refresh with new idToken. how to handle the refresh token service in AWS Cognito using amplify-js. I tried with Auth.currentSession() I will call this for every 1 hour but it's not working for me.

Upvotes: 29

Views: 48724

Answers (5)

Aneesh
Aneesh

Reputation: 141

if you are using amplify 6+ and react add this line

 import 'aws-amplify/auth/enable-oauth-listener';

in app.tsx then it will handle refresh token automatically

Upvotes: 1

sc00ter
sc00ter

Reputation: 579

Calling Auth.currentSession() should solve your problem. Amplify-js abstracts the refresh logic away from you.

Under the hood currentSession() gets the CognitoUser object, and invokes its class method called getSession(). It's this method, that does the following:

  1. Get idToken, accessToken, refreshToken, and clockDrift from your storage.
  2. Validate the tokens (i.e. idToken, and accessToken) to see if they have expired or not.
  3. If tokens are valid, return current session.
  4. If tokens are expired, invoke the refreshSession() method of the CognitoUser class, which communicates to the AWS Identity Provider to generate a new set of tokens.

All you have to do now is either:

  1. Make sure to call Auth.currentSession() at regular intervals
  2. Always call Auth.currentSession() to get your token for each http request that you make.

You could use a wrapper like this:

const getAccessJwtToken = async () => {
  // Auth.currentSession() checks if token is expired and refreshes with Cognito if needed automatically
  const session = await Auth.currentSession();
  return session.getAccessToken().getJwtToken();
};

Lastly, this github discussion also introduces a very good manual way to refresh your token and introduces a use case for when you should explore that option.

Upvotes: 52

Austin Wolfe
Austin Wolfe

Reputation: 389

This will hand you back an AccessToken and a idToken.

fetch("https://cognito-idp.<cognito-user-pool-region>.amazonaws.com/", {
    headers: {
        "X-Amz-Target": "AWSCognitoIdentityProviderService.InitiateAuth",
        "Content-Type": "application/x-amz-json-1.1",
    },
    mode: 'cors',
    cache: 'no-cache',
    method: 'POST',
    body: JSON.stringify({
        ClientId: "<cognito-user-pool-client-id>",
        AuthFlow: 'REFRESH_TOKEN_AUTH',
        AuthParameters: {
            REFRESH_TOKEN: "<cognito-refresh-toke>",
            //SECRET_HASH: "your_secret", // In case you have configured client secret
        }
    }),
}).then((res) => {
    return res.json(); // this will give jwt id and access tokens
});

Upvotes: 5

PersianIronwood
PersianIronwood

Reputation: 780

I have used the 'amazon-cognito-identity-js' and refreshed the toke every time it expired and it solved my problem , here is a code snippet for the tricky getJwtToken part :

    getJwtToken() {
    if (!this.activeUser) {
      return null;
    }

    const signInUserSession = this.activeUser.getSignInUserSession();
    const idToken = signInUserSession ? signInUserSession.getIdToken() : null;

    if (!idToken || idToken.getExpiration() * 1000 <= Date.now()) {
      if (!signInUserSession.isValid()) {
        const refreshToken = signInUserSession.getRefreshToken();
        return new Promise((resolve) => {
          this.activeUser.refreshSession(refreshToken, (err, session) => {
            if (err) {
              resolve(this.logout());
            }
            this.activeUser.setSignInUserSession(session);
            resolve(session.getIdToken().getJwtToken());
          })
        });
      }
      return Promise.resolve(idToken.getJwtToken());
    }

    return Promise.resolve(idToken.getJwtToken());
  }

Upvotes: 0

thomasmichaelwallace
thomasmichaelwallace

Reputation: 8464

Amplify will automatically keep the session fresh so long as it's active (i.e. the user is making api calls, etc.).

If you want to force the session to stay active, even though they are not actively using your API, then the easiest thing to do would be to call Auth.currentAuthenticatedUser() at regular intervals.

Upvotes: 8

Related Questions