Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
Dan Herman Avatar asked Jan 19 '18 14:01

Dan Herman


2 Answers

The correct solution as of 2021 is to call await Auth.currentAuthenticatedUser({bypassCache: true}).

like image 193
andreialecu Avatar answered Sep 22 '22 06:09

andreialecu


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);
}
like image 33
Zohaib Ijaz Avatar answered Sep 24 '22 06:09

Zohaib Ijaz