Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve raw accessToken and idToken in aws-amplify js v6

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.

like image 330
Aliaksei Stadnik Avatar asked Oct 11 '25 12:10

Aliaksei Stadnik


1 Answers

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.

like image 151
Ankush Jain Avatar answered Oct 16 '25 11:10

Ankush Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!