← JSON Web Tokens
JWT·Guide
All tools

JSON Web Tokens

A JWT (RFC 7519) is three Base64URL segments separated by dots: a JSON header naming the algorithm (alg) and often a key (kid), a JSON payload of claims (sub, exp, iat, roles…), and the signature of header.payload. Apps send them as bearer tokens; anyone can read the payload, only the key holder can sign it.

1The JsonWebToken library

lib/jwt.js is a JavaScript module with no user interface. It exports JsonWebToken, a class whose instances are decoded tokens; it imports lib/base64.js and lib/pem.js itself. Verifying and signing use WebCrypto.

import { JsonWebToken } from "../lib/jwt.js";

const token = JsonWebToken.parse(text);
console.log(token.algorithm, token.payload.sub, JsonWebToken.claimStatus(token.payload));
const valid = await token.verify("your-256-bit-secret");

/* change a claim and sign again */
const changed = JsonWebToken.parse(JsonWebToken.encode(token.header, { ...token.payload, role: "admin" }) + ".");
const forged = await changed.sign("your-256-bit-secret");
Method / propertyWhat it does
JsonWebToken.parse(text), new JsonWebToken(text)Decodes a token; throws with a readable message. Whitespace inside the token is ignored.
header, payload, payloadIsJsonThe decoded header and payload (the payload as text when it isn't JSON).
signature, signingInput, algorithm, segmentsThe signature bytes, "header.payload", the header's alg, and the three Base64URL segments.
await token.verify(key, { secretIsBase64 })Whether the signature matches. key is the HMAC secret, a PEM public key or a JWK.
await token.sign(key, { secretIsBase64 })The token text with a new signature (a PEM private key or private JWK for asymmetric algorithms).
JsonWebToken.encode(header, payload)"header.payload" in Base64URL, unsigned.
JsonWebToken.claimStatus(payload, now){ kind, text }: expired, not yet valid, or when it expires; null without exp / nbf.
JsonWebToken.relativeTime(seconds)"in 3 hours", "2 days ago".
JsonWebToken.ALGORITHMS, JsonWebToken.TIME_CLAIMSThe supported algorithms; the claims that hold Unix times.