Skip to content

Instantly share code, notes, and snippets.

@ppanchal97
Created August 12, 2020 20:17
Show Gist options
  • Save ppanchal97/e453efcba8324bf3ce2cf3e83880f7b7 to your computer and use it in GitHub Desktop.
Save ppanchal97/e453efcba8324bf3ce2cf3e83880f7b7 to your computer and use it in GitHub Desktop.
Verifying a cognito ID token using a JS Lambda
// Import dependencies
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
// Example data from https://cognito-idp.<REGION>.amazonaws.com/<POOL-ID>/.well-known/jwks.json
const body = {
"keys": [
{
"alg": "RS256",
"e": "AQAB",
"kid": "yrCCyj+mnuUInXCOD4fBpc92yqnfIpEdLYGuigLUYFYUX6PE=",
"kty": "RSA",
"n": "hWb86QL4-aBQ-msUi4BERF78yiwSLWCwc7bqpcnwC3aFFbanw2XLoy4Uq3_SoBhEpOHUV051Iz4qf41AasaiQnaG5hprUDTQyYjKYQiN1a9p8cqynyrHFH8ZtqCUpAdLH3r799yoOQlku7S_AEiyUoQhzS7TySklG_N5ufhgqaeqj85Ex5SaH53zHqHtpC6qsuPu51_cqbWsTqUOoV_JH6axGOEU1yNAbtuU86wLZo6RxXCXshpSX2S402GxgFvQLCL3Tno2Xwc9TlzQSzYwUJZH5CCi1qZtlEJOutKKNdUOsaEOIYgRhR0jC9Q",
"use": "sig"
},
{
"alg": "RS256",
"e": "AQAB",
"kid": "KdZbhRyRrLuWK/cq9pneewq5Zfwefm10=",
"kty": "RSA",
"n": "s5zHugpZZBM9cEiwKbrjXIHj0vxBo87cb48bp&*B:SD*YANA:*npdsfdDt8dovd_GMUdelefRENuIumLc3HkkPU0uyNrfHoVE4XfZEDHyopXRW99_IsiDt93xuVL3-1AtuNDYLJwrV5-pNFaDS5ujaobpd;saad5ss7LzI5ubhKhvblUa0k74CfpsV0bCWQiG-jCkhgB*LADSNaUHPvap-kTl7cGH&B*P(b7qpn82y30pyn8r39yrn83r29yr23meCrig18wJBYIFZtwe6MO&TBNNLSAwqptXTekHewy1MkklvYDvcBtdTXKkeQ",
"use": "sig"
}
]
}
// Validate a token
function validateToken(token) {
let pems = {};
const keys = body['keys'];
for (let i = 0; i < keys.length; i++) {
//Convert each key to PEM
const key_id = keys[i].kid;
const modulus = keys[i].n;
const exponent = keys[i].e;
const key_type = keys[i].kty;
const jwk = { kty: key_type, n: modulus, e: exponent };
const pem = jwkToPem(jwk);
pems[key_id] = pem;
}
// validate the token
const decodedJwt = jwt.decode(token, { complete: true });
if (!decodedJwt) {
console.log("Not a valid JWT token");
return;
}
const kid = decodedJwt.header.kid;
const pem = pems[kid];
if (!pem) {
console.log('Invalid token');
return;
}
jwt.verify(token, pem, function (err, payload) {
if (err) {
console.log("Invalid Token.");
} else {
console.log("Valid Token.");
console.log(payload);
}
});
}
/**
* Handler function
* @param {AWS Serverless Event} event
*/
exports.handler = async (event) => {
const token = event.headers.Authorization.replace("Bearer ", "");
validateToken(token
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment