JWT Signing Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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