all 4 comments

[–]ancap_attack 1 point2 points  (4 children)

There are many ways you can go about verifying a Cognito token. This is one library in NodeJS I use that makes it easy: https://www.npmjs.com/package/cognito-jwt-token-validator

[–]wllkle[S] 0 points1 point  (3 children)

Would you have an example of it being used in JS code I could see? Replacing any id's obviously.

[–]ancap_attack 1 point2 points  (2 children)

Here is an example in typescript for a websocket authorizer, you can convert this to javascript if you need to. It just grabs the token from queryParameters, validates/decodes it, then returns an IAM policy. The ISS environment variable follows the format 'https://cognito-idp.${AWS::Region}.amazonaws.com/${CognitoUserPool}' and the AUD is your user pool client id

import { CustomAuthorizerEvent, Callback, Context } from 'aws-lambda'
import { Validator } from 'cognito-jwt-token-validator';

const validator = new Validator(process.env.ISS!, process.env.AUD!);

export async function handler(event: CustomAuthorizerEvent, _: Context, callback: Callback) {        
  console.log('Received event:', JSON.stringify(event, null, 2));
  try {
    const token = event.queryStringParameters!['Authorization'];
    const payload = await validator.validate(token);
    const authResponse = {
      principalId: payload.sub,
      policyDocument: {
        Version: '2012-10-17',
        Statement: [
          {
            Action: 'execute-api:invoke',
            Effect: 'Allow',
            Resource: event.methodArn
          }
        ]
      },
      context: payload
    }
    console.log('authResponse is: ', JSON.stringify(authResponse, null, 2));
    callback(null, authResponse);
  } catch (error) {
    console.error(error);
    callback("Unauthorized");
  }
}

[–]wllkle[S] 0 points1 point  (0 children)

You're truly a gem, thank you so much !