aws-amplify Authentication...how to access tokens on successful Auth.signIn?

25,424

Solution 1

Auth.currentSession().then(res=>{
  let accessToken = res.getAccessToken()
  let jwt = accessToken.getJwtToken()
  //You can print them to see the full objects
  console.log(`myAccessToken: ${JSON.stringify(accessToken)}`)
  console.log(`myJwt: ${jwt}`)
})

Solution 2

Auth.currentSession() will return a CognitoUserSession containing accessToken, idToken, and refreshToken.

The CognitoUserSession is actually the following: CognitoUserSession {idToken: CognitoIdToken, refreshToken: CognitoRefreshToken, accessToken: CognitoAccessToken, clockDrift: 0}

Accessing pairs within that object can be achieved through straightforward dot notation at this point.


Example: Retrieve the accessToken and log to console

Auth.currentSession().then(data => console.log(data.accessToken));

The result will be a CognitoAccessToken in the form CognitoAccessToken { jwtToken: '', payload: ''}

If you just want the jwtToken within the CognitoAccessToken, it's just dot notation all the way down (with log to console example):

Auth.currentSession().then(data => console.log(data.accessToken.jwtToken));

Note: This method also refreshes the current session if needed (reference).

Solution 3

I believe you can do

Auth.currentCredentials(credentials => {
  const tokens = Auth.essentialCredentials(credentials);
})

where essentialCredentials will return all of the tokens

Hope this helps.

Solution 4

Angular 9, getting JWT token from current session :

import Auth from '@aws-amplify/auth';

Auth.currentSession().then(data => console.log("JWT", data.getAccessToken().getJwtToken()));
Share:
25,424
spencewine
Author by

spencewine

Updated on July 09, 2022

Comments

  • spencewine
    spencewine almost 2 years

    I'm trying to figure out how to access the accessToken, refreshToken, and idToken that I receive back from aws-amplify using the Auth library.

    example in docs: https://aws.github.io/aws-amplify/media/authentication_guide.html

    example of my usage:

    const user = await Auth.signIn(email, password);

    user has a bunch of properties that are inaccessible including everything I need. In the docs, it's unclear how to get to these properties because the examples all log the result. Any ideas?