Skip to content

Instantly share code, notes, and snippets.

@Aupajo
Last active October 13, 2023 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aupajo/be628f6f88aa9c06681aaf114bec5720 to your computer and use it in GitHub Desktop.
Save Aupajo/be628f6f88aa9c06681aaf114bec5720 to your computer and use it in GitHub Desktop.
Using Jose to generate a secret, JWKS, sign a JWT, and verify (useful for testing)
import * as jose from "jose";
const ONE_HOUR_FROM_NOW = Math.floor(Date.now() / 1000) + 60 * 60;
// Mock this, for example
const jwt = {
// Standard claims
sub: "https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001Sw9AAAS",
iss: "urn:example:issuer",
aud: "urn:example:audience",
exp: ONE_HOUR_FROM_NOW,
// Some extra claims
given_name: "John",
picture: "https://c.eu6.content.force.com/profilephoto/005/F",
};
const alg = "RS256";
const { privateKey, publicKey } = await jose.generateKeyPair(alg);
const jwk = await jose.exportJWK(publicKey);
const signedJWT = await new jose.SignJWT(jwt)
.setProtectedHeader({ alg })
.setIssuedAt()
.sign(privateKey);
// This is the JWT you might receive in an HTTP request
console.log("JWT:", signedJWT);
// What you might get from a JSON Web Key Store HTTP request
const jwks = {
keys: [jwk],
};
console.log("JWKS:", jwks);
const joseJWKS = jose.createLocalJWKSet(jwks);
// Alternatively, mock the JWKS address
// mockURL("http://example/jwks", jwks);
// const joseJWKS = jose.createRemoteJWKSet("http://example/jwks");
// Verify the JWT against the JWKSet
const { payload, protectedHeader } = await jose.jwtVerify(signedJWT, joseJWKS, {
issuer: "urn:example:issuer",
audience: "urn:example:audience",
});
console.log("Decoded JWT:", payload);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment