Security·6 min read·By the developer of StackUtils

JWT Explained: How JSON Web Tokens Work

JWT tokens are in every Authorization header, but most developers never look inside them. Learn the header.payload.signature structure, common claims, signing algorithms, and the security mistakes to avoid.

What a JWT Is

A JSON Web Token (RFC 7519) is a small JSON object of “claims” — who the user is, who issued the token, when it expires — packaged so that a server can check it was not altered. After login, an auth server issues the token and the client sends it back on each request, usually as Authorization: Bearer <token>.

Almost every JWT you meet is a JWS (JSON Web Signature, RFC 7515): signed, not encrypted. The signature proves integrity and origin; it hides nothing. Anyone holding the token can read the payload. Encrypted tokens (JWE, RFC 7516) exist but have five dot-separated parts instead of three and are much rarer.

Anatomy of a Real Token

This token was signed with HS256 and the secret demo-secret-do-not-use:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0IiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNzY3MjI1NjAwLCJleHAiOjE3NjcyMjY1MDB9.KmrwK2NX5fD9v6TykC8Lx99Qt4a5h2thMKSc2kFHmZc

Each part is base64url without padding (the URL-safe alphabet with - and _, and no =). The first two decode to JSON:

// header
{ "alg": "HS256", "typ": "JWT" }

// payload
{ "sub": "1234", "name": "Alice", "iat": 1767225600, "exp": 1767226500 }

Both start with eyJ because that is what {" looks like in Base64 — a quick way to recognise a JWT in logs. The third part is the signature: 32 raw bytes of HMAC-SHA256, Base64url-encoded. Decoding a payload needs no key:

function decodeJwtPayload(token) {
  const part = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
  const padded = part.padEnd(part.length + ((4 - (part.length % 4)) % 4), "=");
  const json = new TextDecoder().decode(
    Uint8Array.from(atob(padded), (c) => c.charCodeAt(0)),
  );
  return JSON.parse(json);
}
// → { sub: "1234", name: "Alice", iat: 1767225600, exp: 1767226500 }

The padding and UTF-8 steps matter: a plain atob(part) breaks on -/_ and garbles non-ASCII names. The Base64 guide explains both alphabets.

How the Signature Is Computed

The signature covers the exact string base64url(header) + "." + base64url(payload). In Node.js, the token above is produced like this:

const crypto = require("node:crypto");
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");

const data = b64url({ alg: "HS256", typ: "JWT" }) + "." +
             b64url({ sub: "1234", name: "Alice", iat: 1767225600, exp: 1767226500 });
const sig = crypto.createHmac("sha256", "demo-secret-do-not-use")
                  .update(data).digest("base64url");
const token = data + "." + sig;

Because the signature is over the encoded strings, a token must be verified exactly as received. Decoding, re-serialising the JSON (key order, whitespace) and re-encoding produces different bytes and an “invalid signature” error even though the claims are identical.

Registered Claims

ClaimMeaningWhat the verifier should do
issIssuerCompare with the expected issuer URL exactly.
subSubject (usually a user ID)Use as the identity; it is a string, not necessarily numeric.
audAudience: string or arrayReject unless it contains this API's identifier.
expExpiry, seconds since the Unix epochReject if now ≥ exp, allowing a small clock-skew leeway (e.g. 30–60 s).
nbfNot beforeReject if now < nbf (same leeway).
iatIssued atInformational; can enforce a maximum token age.
jtiUnique token IDStore used IDs if you need one-time tokens or a revocation list.

Times are seconds, not milliseconds. Writing exp: Date.now() + 900000 creates a token that expires around the year 58,800; the correct form is Math.floor(Date.now() / 1000) + 900. In the sample token, iat 1767225600 is 2026-01-01 00:00:00 UTC and exp is 15 minutes later — you can check values like these with the Unix timestamp converter.

Choosing an Algorithm

algTypeKeysUse when
HS256HMAC + SHA-256One shared secret signs and verifiesThe issuer and the verifier are the same service, or fully trust each other.
RS256RSA PKCS#1 v1.5 + SHA-256Private key signs; public key verifiesMany services or third parties verify; publish public keys as a JWKS.
ES256ECDSA P-256 + SHA-256Private / public key pairSame as RS256 with much smaller keys and signatures (64 bytes vs 256 for RSA-2048).
EdDSAEd25519Private / public key pairModern alternative where your libraries support it.
noneNo signature—Never accept it on a server.

With HS256 the secret is the only protection. RFC 7518 requires a key at least as long as the hash output — 256 bits — and that means 32 random bytes, not a memorable phrase. Anyone who captures a single token can try guesses offline as fast as their hardware allows, so a short or dictionary-word secret can be recovered and used to mint valid tokens. Generate it with crypto.randomBytes(32) or a password generator set to a long random string.

The Two Classic Attacks: alg=none and Algorithm Confusion

alg: none

RFC 7519 defines “unsecured” JWTs with {"alg":"none"} and an empty signature. An attacker takes a valid token, changes sub to an admin ID, sets alg to none and deletes the signature:

eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.<edited payload>.

A verifier that trusts the header's alg skips the signature check and accepts it.

RS256 → HS256 confusion

A server verifies RS256 tokens with its public key — which is public. The attacker creates a token with alg: HS256 and signs it with HMAC using the bytes of that public key as the secret. A library that reads alg from the token and calls verify(token, publicKey) runs HMAC with the same “secret” and the signature matches.

Both attacks have the same fix: the server decides the algorithm, never the token. Every mainstream library lets you pin it:

// jsonwebtoken
jwt.verify(token, publicKey, { algorithms: ["RS256"], audience: "api://orders" });

// jose
await jwtVerify(token, publicKey, {
  algorithms: ["RS256"],
  issuer: "https://auth.example.com",
  audience: "api://orders",
});

A minimal hand-written HS256 check shows what “verify” must include. It rejects the none token above with unexpected alg none:

function verifyHs256(token, secret) {
  const [h, p, s] = token.split(".");
  const header = JSON.parse(Buffer.from(h, "base64url").toString());
  if (header.alg !== "HS256") throw new Error("unexpected alg " + header.alg);

  const expected = crypto.createHmac("sha256", secret).update(h + "." + p).digest();
  const given = Buffer.from(s, "base64url");
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected))
    throw new Error("bad signature");

  const claims = JSON.parse(Buffer.from(p, "base64url").toString());
  if (typeof claims.exp !== "number" || Date.now() / 1000 >= claims.exp)
    throw new Error("expired");
  return claims;
}

In production, use a maintained library rather than this function; it also handles nbf, aud, clock skew and key rotation. Related header fields deserve the same suspicion: never fetch keys from a jku or x5u URL supplied by the token, and treat kid only as a lookup key into your own key set.

JWT or Server Session?

ConcernJWT access tokenOpaque session ID
Where state livesIn the tokenIn a server store (Redis, database)
VerificationSignature check, no lookupOne store lookup per request
Logout / revocationNot immediate: valid until exp unless you keep a denylistImmediate: delete the session
Payload visibilityReadable by the client and anyone who intercepts itOpaque
Good fitAPIs verified by several services, short-lived tokensA single web app with server-rendered pages

The usual compromise is a short-lived access token (5–15 minutes) plus a refresh token that is stored server-side, rotated on every use and revocable. For browsers, an HttpOnly, Secure, SameSite cookie keeps the token out of reach of injected scripts; localStorage does not. Cookies bring CSRF back into scope, which SameSite=Lax or Strict plus a CSRF token handles.

Debugging Common Errors

ErrorCheck
jwt malformedYou passed the whole header value. Strip the "Bearer " prefix and any quotes; a JWS has exactly two dots.
invalid signatureWrong secret or key; secret stored Base64-encoded but used as a raw string (or the reverse); token edited or re-serialised; RS256 token verified with the wrong key from the JWKS (check kid).
jwt expired right after loginexp written in milliseconds or seconds mixed up; server clock drift — compare exp with the current Unix time.
jwt audience invalidaud is an array or a different identifier than the one configured; the token was issued for another API.
Works in one service, fails in anotherDifferent allowed algorithms, issuer string with or without a trailing slash, or a stale cached JWKS after key rotation.

To look inside a token while debugging, paste it into the JWT decoder. It decodes the header and payload in your browser and shows timestamps as dates with the expiry status, but it deliberately does not verify signatures — that must happen on your server with the real key. To create test tokens with chosen claims and expiry, the JWT generator signs HS256 tokens with a secret you provide. Don't paste production tokens or secrets into any website you do not control.

Inspect or create test JWTs

Decode a token's header and claims, or generate a signed HS256 token for local testing.