9

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.

Dan Herman
  • 1,395
  • 1
  • 15
  • 26
  • won't `currentCredentials` https://aws.github.io/aws-amplify/api//classes/auth_auth_.authclass.html#currentcredentials return up to date tokens for you? – iurii Jan 28 '18 at 19:07

5 Answers5

10

The correct solution as of 2021 is to call:

await Auth.currentAuthenticatedUser({bypassCache: true})
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
andreialecu
  • 3,639
  • 3
  • 28
  • 36
2

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);
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

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.

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Yassou
  • 43
  • 7
0

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)
tofarr
  • 7,682
  • 5
  • 22
  • 30
Nouman
  • 410
  • 1
  • 8
  • 15
  • 2
    Do you know which version of Amplify has this? In the version I'm using I get `User.refreshSession is not a function` – Dan Herman Oct 11 '18 at 13:47
0

@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
    }
  }
Nick
  • 175
  • 5
  • 13