Tutorial

A Complete Guide to JWT Authentication in Web Applications

Token structure, signing algorithms, refresh tokens, rotation, and revocation strategies for secure JWT auth in production web apps.

On this page

  1. Introduction
  2. Anatomy of a JWT
  3. Choosing a Signing Algorithm
  4. The Access and Refresh Token Pattern
  5. Refresh Token Rotation and Reuse Detection
  6. Client-Side Storage and the XSS Question
  7. Revocation in a Stateless System
  8. Token Lifetimes, Key Rotation, and JWKS
  9. Conclusion

Introduction

JSON Web Tokens have become the default stateless authentication mechanism for web applications and APIs. They are compact, self-contained, and travel well across domains and services. They are also, far too often, implemented incorrectly: tokens signed with weak keys, refresh tokens that never expire, access tokens stored in localStorage where any injected script can read them, and no revocation story at all. A JWT system done well is secure and scalable; done poorly, it is an open door with a familiar name on it.

This guide covers the complete lifecycle of a JWT-based authentication system: the structure of a token, the choice of signing algorithm, the access-and-refresh-token pattern, rotation and reuse detection, storage on the client, and the hard problem of revocation in a stateless system. We will use Node.js and TypeScript for examples, but the concepts apply to any stack.

Anatomy of a JWT

A JWT is three base64url-encoded segments separated by dots: header.payload.signature. The header declares the algorithm and token type. The payload carries claims — the assertions the token makes about the bearer. The signature proves that the issuer produced the token and that it has not been tampered with.

// Header
{ "alg": "HS256", "typ": "JWT" }
// Payload (claims)
{
  "sub": "user-42",
  "iss": "https://auth.example.com",
  "aud": "https://api.example.com",
  "role": "admin",
  "iat": 1736832000,
  "exp": 1736835600,
  "jti": "f1c2d3e4-..."
}

The registered claims matter. sub identifies the subject. iss and aud constrain who may issue and consume the token — always verify aud matches your service, or a token minted for one service will be accepted by another. iat (issued at), exp (expiration), and nbf (not before) bound the token’s validity in time. jti is a unique token ID, essential for revocation and refresh-token reuse detection. Custom claims (role above) are fine, but keep the payload small — every byte travels on every request, and a bloated token inflates bandwidth and base64-decode cost.

A critical point: the payload is encoded, not encrypted. Anyone who obtains the token can read every claim by base64-decoding the payload. Never put a secret, a password, or personally sensitive data in a JWT payload. If you need confidentiality, encrypt the token (JWE) rather than merely signing it.

Choosing a Signing Algorithm

The algorithm choice is a security decision, not a default. HS256 (HMAC with SHA-256) uses a single shared secret for both signing and verification. It is simple but creates a key-distribution problem: every service that verifies the token must hold the secret, and any service that holds the secret can mint tokens. RS256 (RSA signature with SHA-256) uses a private key to sign and a public key to verify, so verifying services need only the public key and cannot forge tokens. For a multi-service system, RS256 or ES256 (ECDSA) is almost always the right choice.

Beware the algorithm-confusion attack. If your verifier accepts the alg from the token header and you have a public key configured for RS256, an attacker can craft a token with alg: "none" or alg: "HS256" and sign it using your public key as the HMAC secret. The defense is to pin the expected algorithm server-side and reject any token that declares a different one. Every mature JWT library lets you specify the algorithm explicitly — do so, and never accept alg: "none".

import jwt from "jsonwebtoken";

// Signing (auth service holds the private key)
const token = jwt.sign(
  { sub: userId, role: "user" },
  process.env.JWT_PRIVATE_KEY!, // PEM-encoded RSA private key
  { algorithm: "RS256", expiresIn: "15m", issuer: "auth.example.com", audience: "api.example.com", jwtid: crypto.randomUUID() },
);

// Verifying (API service holds only the public key)
const claims = jwt.verify(token, process.env.JWT_PUBLIC_KEY!, {
  algorithms: ["RS256"], // pin the algorithm — never omit this
  issuer: "auth.example.com",
  audience: "api.example.com",
});

The Access and Refresh Token Pattern

Access tokens are short-lived — fifteen minutes is a common ceiling. They authorize API calls and are sent on every request. Refresh tokens are long-lived — days or weeks — and are used only to obtain new access tokens from the authorization server. The split exists because an access token, if stolen, is valid for only a short window, while a refresh token can be kept on a secure path (an HTTP-only cookie) and rotated on every use.

async function login(userId: string, res: Response) {
  const accessToken = signAccessToken(userId);
  const refreshToken = await issueRefreshToken(userId); // store hash in DB
  res.cookie("access_token", accessToken, {
    httpOnly: true, secure: true, sameSite: "strict", maxAge: 15 * 60 * 1000,
  });
  res.cookie("refresh_token", refreshToken, {
    httpOnly: true, secure: true, sameSite: "strict", path: "/auth/refresh", maxAge: 7 * 24 * 60 * 60 * 1000,
  });
}

Notice the refresh-token cookie is scoped to path: "/auth/refresh". It is sent only on requests to the refresh endpoint, not on every API call, which reduces the surface over which the long-lived credential is exposed. Both cookies are httpOnly (inaccessible to JavaScript), secure (sent only over HTTPS), and sameSite: "strict" (not sent on cross-site requests, defeating CSRF).

Refresh Token Rotation and Reuse Detection

Rotation means every refresh token is single-use: presenting a refresh token returns a new access token and a new refresh token, and the old refresh token is invalidated. Rotation limits the damage of a stolen refresh token — the thief and the legitimate user race to use it, and whoever loses finds their token dead.

Reuse detection makes rotation genuinely secure. Store a hash of each issued refresh token alongside the user and a “revoked” flag. When a refresh token is presented, look up its hash. If it is valid, issue a new pair and mark the old token consumed. If it has already been consumed, you have detected reuse — a stolen token is being replayed. The correct response is to revoke the entire family: invalidate every refresh token for that user and force a full re-login. This is the single most effective defense against refresh-token theft.

async function refresh(oldRefreshToken: string) {
  const hash = sha256(oldRefreshToken);
  const record = await db.refreshToken.findUnique({ where: { hash } });
  if (!record) throw new AuthError("invalid token");
  if (record.revoked) {
    // Reuse detected — revoke the whole family.
    await db.refreshToken.updateMany({ where: { userId: record.userId }, data: { revoked: true } });
    throw new AuthError("reuse detected; all sessions revoked");
  }
  if (record.expiresAt < new Date()) throw new AuthError("expired");
  // Rotate: consume old, issue new.
  await db.refreshToken.update({ where: { id: record.id }, data: { revoked: true } });
  const newRefresh = crypto.randomBytes(32).toString("base64url");
  await db.refreshToken.create({ data: { userId: record.userId, hash: sha256(newRefresh), expiresAt: addDays(new Date(), 7) } });
  return { accessToken: signAccessToken(record.userId), refreshToken: newRefresh };
}

Client-Side Storage and the XSS Question

Where you store the access token on the client is a real security decision. localStorage is readable by any JavaScript running on the page, so a single cross-site scripting (XSS) vulnerability hands the attacker the user’s access token. The httpOnly cookie is not readable by JavaScript, which closes that hole, but it is sent automatically on every request to the cookie’s origin, which makes CSRF a concern — mitigated by SameSite and a CSRF token on state-changing requests.

For a same-origin SPA and API, httpOnly cookies are the safer default. For a third-party API consumed from the browser (where cookies cannot be sent cross-origin without CORS credentials), an in-memory access token refreshed from an httpOnly refresh-token cookie is a common compromise: the access token survives only until the page reloads, and the refresh token is never exposed to JavaScript. Avoid localStorage unless you have a specific reason and a strong CSP.

Revocation in a Stateless System

The defining property of a JWT is statelessness: the verifier needs no database lookup, because the signature is the proof. Revocation breaks statelessness — to revoke a token before its exp, the verifier must consult some state. There are three practical approaches.

The first is a blocklist of revoked jti values, checked on every request. This is a database or Redis lookup on the hot path, which reintroduces the latency you adopted JWTs to avoid, but it is simple and correct. Keep the blocklist small by pruning entries whose tokens have naturally expired. The second is short access-token lifetimes plus refresh-token revocation: accept that a stolen access token is valid for its fifteen-minute life, and invest your revocation effort in the refresh token, which you control in the database. When a user logs out or you detect compromise, revoke their refresh tokens; the access token dies on its own within minutes. This is the most common production approach. The third is a token version claim: store a per-user version number in the payload and in the database, and reject tokens whose version is stale. Bumping the version (on logout, password change, or role change) invalidates every outstanding token for that user in one update.

async function verifyWithRevocation(token: string) {
  const claims = jwt.verify(token, publicKey, { algorithms: ["RS256"], audience: "api.example.com" }) as Claims;
  const user = await db.user.findUnique({ where: { id: claims.sub }, select: { tokenVersion: true } });
  if (claims.v !== user.tokenVersion) throw new AuthError("token superseded");
  return claims;
}

Token Lifetimes, Key Rotation, and JWKS

The lifetime of an access token is a security-versus-UX trade-off encoded as a number. A shorter lifetime limits the damage of a stolen token but forces more frequent refreshes, each of which is a round trip and a potential failure. A longer lifetime is convenient but widens the window in which a stolen token is valid. Fifteen minutes is the common compromise: short enough that a stolen access token is useful for minutes rather than hours, long enough that a user reading a page is not interrupted by a refresh. For a high-value operation (a banking transfer), issue a token with a lifetime of a single minute or require step-up authentication; for a low-value read-heavy app, thirty minutes is defensible. The choice should be explicit and documented, not the library default.

Refresh-token lifetimes are a different trade-off. A refresh token valid for seven days means a user who returns within a week is still logged in, which is good UX but a credential sitting in a cookie for a week. Distinguish absolute expiration (the token is dead at a fixed date regardless of use) from sliding expiration (each refresh extends the deadline). Sliding expiration keeps a regularly-active user logged in indefinitely, which is convenient but means a stolen refresh token that is used frequently never expires; absolute expiration caps the damage at the cost of occasionally asking an active user to re-login. For most consumer apps, an absolute lifetime of thirty days with sliding renewal up to that cap is a reasonable balance.

Key rotation is the procedure that lets you change the signing key without invalidating every outstanding token. The mechanism is the kid (key id) header claim: each token is signed with a specific key and carries the id of that key, and the verifier selects the key by id. To rotate, you generate a new key pair, add it to the set of valid signing keys, and begin signing new tokens with it. Tokens signed with the old key continue to verify until they expire, because the verifier still has the old public key. Once every old token has expired, you remove the old key from the set. The rotation is gradual and non-disruptive, and at no point is a valid token rejected.

For a distributed system where verifying services cannot share a static key file, expose the public keys via a JWKS (JSON Web Key Set) endpoint. Each verifying service fetches /.well-known/jwks.json, caches it, and looks up the key by kid. Rotation is then a matter of publishing the new key in the JWKS endpoint; every verifier picks it up on the next fetch. Cache the JWKS with a short TTL and refresh on a cache miss for an unknown kid, so a newly-rotated key is fetched on demand. Rate-limit the JWKS fetch and fall back to a cached copy on fetch failure, so a JWKS endpoint outage does not take down authentication. This is how Auth0, Okta, and every OIDC provider distribute their keys, and it is the pattern to follow when you operate your own issuer.

import { createRemoteJWKSet } from "jose";

// A verifier that fetches and caches the JWKS, selecting the key by kid.
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));

async function verify(token: string) {
  const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
    algorithms: ["RS256"],
    issuer: "auth.example.com",
    audience: "api.example.com",
  });
  return payload; // the key was selected by protectedHeader.kid automatically
}

The rotation procedure deserves a runbook, because the first time you need it is not the time to invent it. Document the steps: generate the new key, publish it, switch signing to the new key, wait for the old tokens to expire (the maximum access-token lifetime, plus a margin), then remove the old key. Test the rotation in staging by rotating, verifying that old tokens still work and new tokens are signed with the new key, and confirming that removing the old key after expiry rejects only the expired tokens. A rotation you have rehearsed is a rotation you can do at noon; one you have not is a rotation you postpone until it is an emergency.

Conclusion

A secure JWT system rests on a handful of disciplined choices: sign with an asymmetric algorithm and pin it, keep access tokens short-lived and refresh tokens rotated and reuse-detected, store tokens in httpOnly cookies rather than localStorage, verify iss, aud, and exp on every request, and have a revocation story before you need it. JWTs are not magic — they are a signed envelope whose security is entirely determined by how you issue, store, and verify them. Get those mechanics right and you get a scalable, stateless auth system; get them wrong and you get a familiar vulnerability with a standards-track name on it.

Related Examples