Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 929
spencewine Avatar asked Feb 13 '18 23:02

spencewine


People also ask

Does amplify automatically refresh tokens?

By default, Amplify will automatically refresh the tokens for Google and Facebook, so that your AWS credentials will be valid at all times.

How do you authenticate with tokens with Cognito?

Authenticating with tokensWhen a user signs into your app, Amazon Cognito verifies the login information. If the login is successful, Amazon Cognito creates a session and returns an ID, access, and refresh token for the authenticated user.


2 Answers

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}`) }) 
like image 103
Omar Avatar answered Oct 12 '22 11:10

Omar


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).

like image 35
xrpza Avatar answered Oct 12 '22 11:10

xrpza