To create a JSON Web Token (JWT), use the encodeJWT() function. This function requires three arguments: a stringified header object, a stringified payload object, and a Uint8Array containing the signature.
Before calling encodeJWT(), you must:
- Prepare a JSON header (e.g., specifying the algorithm using
joseAlgorithmHS256). - Prepare a JSON payload (e.g., setting an expiration
exp or custom claims). - Generate a signature using a cryptographic method (like
crypto.subtle.sign) and the createJWTSignatureMessage() helper to combine the header and payload for signing.
import { joseAlgorithmHS256, createJWTSignatureMessage, encodeJWT } from "@oslojs/jwt";
const headerJSON = JSON.stringify({
alg: joseAlgorithmHS256,
typ: "JWT"
});
const payloadJSON = JSON.stringify({
exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 30,
name: "John Doe"
});
const signatureBuffer = await crypto.subtle.sign("HMAC", key, createJWTSignatureMessage(headerJSON, payloadJSON));
const jwt = encodeJWT(headerJSON, payloadJSON, new Uint8Array(signatureBuffer));