Access Cognito values in Lambda function

JWT token that is part of the Authorization header is accessible inside the Lambda functions as well. In the below example, I am decoding the JWT token value and checking the values inside it.

const res = require('./common/res');
const jwtDecode = require('jwt-decode');

const getToken = (header) => {
    return jwtDecode(new Buffer(header.split(" ")[0]).toString());
}

module.exports.handler = async event => {
    console.log(`Cognito User`, event);
    console.log(getToken(event.headers.Authorization));

    return res({body: {
        message: 'This is a test profile message',
        source: event.cognitoPoolClaims // Cognito Pool Claims
    }})
}

/** 
JWT Payload Data

{
  sub: 'b9f37dec-b5bf-4eb1-989f-ae7026715c3d',
  'cognito:groups': [ 'admins' ],
  email_verified: true,
  'cognito:preferred_role': 'arn:aws:iam::XXXXXXXXXX:role/admin-users-serverless-docs',
  iss: 'https://cognito-idp.ap-southeast-1.amazonaws.com/ap-southeast-1_lBwBP9VEb',
  'cognito:username': 'dhaval_admin',
  'cognito:roles': [ 'arn:aws:iam::XXXXXXXXXX:role/admin-users-serverless-docs' ],
  aud: '7fdcfo50mhcqm5ui0pl0lrc88f',
  event_id: '8f233e4a-cd77-4792-89cd-4a29148ecdc2',
  token_use: 'id',
  auth_time: 1595657572,
  exp: 1595661172,
  iat: 1595657572,
  email: 'dhaval@appgambit.com'
}
**/

Last updated

Was this helpful?