Dan Herman
Dan Herman

Reputation: 1505

How can I force a cognito token refresh from the client

I am using aws amplify and I know that the tokens get automatically refreshed when needed and that that is done behind the scenes.

What I need to do is change a custom attribute on the user in the cognito user pool via a Lambda backend process. This I can do, and it is working. However, the web client user never sees this new custom attribute and I am thinking the only way they can see it is if the token gets refreshed since the value is stored within the JWT token.

Upvotes: 10

Views: 7625

Answers (5)

andreialecu
andreialecu

Reputation: 3729

The correct solution as of 2021 is to call:

await Auth.currentAuthenticatedUser({bypassCache: true})

Upvotes: 13

Nick
Nick

Reputation: 275

@andreialecu wrote the correct answer. For full code to get the JWT:

static async amplifyRefresh() {
    try {
      const currentUser = await Auth.currentAuthenticatedUser({ bypassCache: true })      
      const currentSession = await Auth.currentSession()      
      const jwt = currentSession.getIdToken().getJwtToken()
      // do what you want
    } catch (error) {
      console.log("error refreshing token: ", error)
      throw error
    }
  }

Upvotes: 0

Nouman
Nouman

Reputation: 410

Undocumented, but you can use the refreshSession method on the User. Your next call to currentAuthenticatedUser and currentSession will have updated profile attributes (and groups)

User = Auth.currentAuthenticatedUser()
Session =  Auth.currentSession()

User.refreshSession(Session.refreshToken)

Upvotes: 0

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

Here is how you can update tokens on demand (forcefully)

import { Auth } from 'aws-amplify';

try {
  const cognitoUser = await Auth.currentAuthenticatedUser();
  const currentSession = await Auth.currentSession();
  cognitoUser.refreshSession(currentSession.refreshToken, (err, session) => {
    console.log('session', err, session);
    const { idToken, refreshToken, accessToken } = session;
    // do whatever you want to do now :)
  });
} catch (e) {
  console.log('Unable to refresh Token', e);
}

Upvotes: 4

Yassou
Yassou

Reputation: 43

Like it's said here:

https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html

The access token and ID token are good for 1 hour. With Amplify you can get the info about the session using currentSession or currentUserInfo in Auth class to be able to retrieve information about tokens.

Upvotes: 0

Related Questions