skip to Main Content

I am using aws-amplify v6 inside my react-native app.

Authentication functionality is working correctly however I could not access raw access/id tokens after login.

Trying to retrieve the tokens like:

import { fetchAuthSession } from "aws-amplify/auth";

...

async getCurrentSession() {
      const session = await fetchAuthSession();
      console.log("Token: ", JSON.stringify(session.tokens?.idToken));
}

However, tokens inside the session are of the type of JwtPayloadStandardFields
and contain only parsed payloads of the tokens i.e.

{
   "payload":{
      "sub":"4ac665ba-2e3c-40a0-93d8-515e2224fe22",
      "email_verified":true,
      "is":"...",
      "cognito:username":"...",
      "origin_jti":"c9f42d85-b7f2-4780-995a-562ff120d6c7",
      "aud":"...",
      "event_id":"2fe27904-8de0-4b53-80b5-abe166f98e9f",
      "token_use":"id",
      "auth_time":1701865836,
      "exp":1702047957,
      "iat":1702044358,
      "jti":"28516f62-0cab-4a5d-a6f1-eb6dff6cadee",
      "email":"xxx"
   }
}

I am wondering how to access actual raw tokens as I need them to pass to API clients.

2

Answers


  1. This is how I am using it in Angular TypeScript with Amplify v6.

    1. Import fetchAuthSession on top.

      import { fetchAuthSession } from "aws-amplify/auth";
      
    2. Then, just apply .toString() method on idToken property.

      var cognitoTokens = (await fetchAuthSession()).tokens;
      
      let rawToken = cognitoTokens?.idToken?.toString();
      let payload = cognitoTokens?.idToken?.payload;
      

      As you can see in the below screenshot, it offers 2 properties.

      enter image description here

      Here is a screenshot that I captured during debugging.

      enter image description here

    I am using "aws-amplify": "^6.0.5" version.

    Login or Signup to reply.
  2. Another option is to use cognitoUserPoolsTokenProvider after you config token-saving properly

    It can use like this.

        import { cognitoUserPoolsTokenProvider } from 'aws-amplify/auth/cognito'
    
        const {idToken, accessToken, refreshToken, ..., username} = await cognitoUserPoolsTokenProvider.authTokenStore.loadTokens()
    

    I am using "aws-amplify": "^6.0.10"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search