Skip to content

Instantly share code, notes, and snippets.

@yossale
Last active Oct 13, 2020
Embed
What would you like to do?
JWT Signing Lambda
const AWS = require("aws-sdk");
const kms = new AWS.KMS();
const util = require('util')
const base64url = require("base64url");
const keyId = '<YOUR_KEY_ID>'
async function sign(headers, payload, key_arn) {
payload.iat = Math.floor(Date.now() / 1000);
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
payload.exp = Math.floor(tomorrow.getTime() / 1000);
let token_components = {
header: base64url(JSON.stringify(headers)),
payload: base64url(JSON.stringify(payload)),
};
let message = Buffer.from(token_components.header + "." + token_components.payload)
let res = await kms.sign({
Message: message,
KeyId: keyId,
SigningAlgorithm: 'RSASSA_PKCS1_V1_5_SHA_256',
MessageType: 'RAW'
}).promise()
token_components.signature = res.Signature.toString("base64")
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
return token_components.header + "." + token_components.payload + "." + token_components.signature;
}
let header = {
"alg": "RS256",
"typ": "JWT"
}
let payload = {
"user_name": "yossale"
}
exports.handler = async (event) => {
console.log("Start")
let res = await sign(header, payload, keyId)
console.log(`JWT token: [${res}]`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment