Last active
August 20, 2023 03:19
-
-
Save pixeldrew/57fdd076b8c43bcd8bf2a5b48108b886 to your computer and use it in GitHub Desktop.
Usint a cert stored in Azure Keyvault to generate an RS256 JWT Token
This file contains hidden or 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
import { SecretClient } from "@azure/keyvault-secrets"; | |
import { DefaultAzureCredential } from "@azure/identity"; | |
import * as jose from "node-jose"; | |
const vaultUrl = `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`; | |
const credential = new DefaultAzureCredential(); | |
const secretClient = new SecretClient(vaultUrl, credential); | |
async function main() { | |
const keyVaultKey = await secretClient.getSecret("jwkdemo"); | |
// keyVault holds certificates in @azure/keyvault-certificates | |
// to get the private key you have to use @azure/keyvault-secrets | |
// make sure certificate is self signed and pem encoded | |
const privateKey = await jose.JWK.asKey(keyVaultKey.value!, "pem"); | |
const publicKey = await jose.JWK.asKey( | |
keyVaultKey?.value?.slice( | |
keyVaultKey?.value?.indexOf("-----BEGIN CERTIFICATE-----"), | |
) ?? "", | |
"pem", | |
); | |
const keystore = jose.JWK.createKeyStore(); | |
const jwk = await keystore.add({ | |
...publicKey.toJSON(), | |
...privateKey.toJSON(true), | |
use: "sig", | |
}); | |
const body = { | |
iss: `https://local.foe.hn`, // serve a json at /.well-known/openid-configuration with the prop jwks_uri to verify and serve the public key out | |
nbf: Math.round(Date.now() / 1000), | |
exp: Math.round(Date.now() / 1000) + 60 * 60 * 4, // 4 hours | |
name: "Bilbo Baggins", | |
}; | |
const token = await jose.JWS.createSign( | |
{ | |
compact: true, | |
fields: { typ: "jwt" }, | |
}, | |
jwk, | |
) | |
.update(JSON.stringify(body)) | |
.final(); | |
console.log(token); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment