Skip to content

Instantly share code, notes, and snippets.

@pixeldrew
Last active August 21, 2023 13:51
Show Gist options
  • Save pixeldrew/6098a8cc7d5793e1ba5ad26d813af0f7 to your computer and use it in GitHub Desktop.
Save pixeldrew/6098a8cc7d5793e1ba5ad26d813af0f7 to your computer and use it in GitHub Desktop.
JWT with vault key using vault encryption
import {
KeyClient,
CryptographyClient,
} from "@azure/keyvault-keys";
import { DefaultAzureCredential } from "@azure/identity";
import { createHash } from "crypto";
const vaultUrl = `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`;
const credential = new DefaultAzureCredential();
const keyClient = new KeyClient(vaultUrl, credential);
const b64url = (input: string | Buffer) => Buffer.from(input).toString("base64url");
const jwk = (input: any) => ({
kid: input.kid.split("/").pop(),
kty: input.kty,
n: b64url(input.n),
e: b64url(input.e),
use: input.keyOps[0],
});
async function main() {
const key = await keyClient.getKey("jwks-trust-realm");
const cryptClient = new CryptographyClient(
key?.id ?? "unknown",
new DefaultAzureCredential(),
);
const header = b64url(
JSON.stringify({
kid: key?.id?.split("/").pop() ?? "unknown",
typ: "JWT",
alg: "RS256",
}),
);
const body = b64url(
JSON.stringify({
iss: "https://somewhere.com",
nbf: Math.round(Date.now() / 1000),
exp: Math.round(Date.now() / 1000) + 60 * 60 * 4, // 4 hours
name: "Bilbo Baggins",
}),
);
const hash = createHash("sha256");
const digest = hash.update(`${header}.${body}`).digest();
const signResult = await cryptClient.sign("RS256", digest);
const token = `${header}.${body}.${b64url(signResult.result as Buffer)}`;
console.log(token);
console.log(JSON.stringify(jwk(key.key), null, 4));
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment