JWT Security

Difficulty: Intermediate

Question

What is a JWT, how is it structured and verified, and where should you store it safely in a browser?

Answer

A JSON Web Token (JWT) is a compact, URL-safe token made of three Base64URL-encoded parts separated by dots: header.payload.signature. The server signs the header and payload with a secret or private key, so anyone can read the claims but nobody can change them without breaking the signature. In a browser, the safest default is to keep it in an HttpOnly, Secure, SameSite cookie rather than localStorage, and to keep access tokens short-lived.

The three parts

  • Header: algorithm and type, for example {"alg":"HS256","typ":"JWT"}.
  • Payload: claims such as sub (user id), exp (expiry), iat (issued at), iss (issuer), aud (audience) and custom ones like role.
  • Signature: HMACSHA256(base64url(header) + "." + base64url(payload), secret) for HS256, or an RSA/ECDSA signature for RS256/ES256.

The payload is encoded, not encrypted. Paste any JWT into a decoder and you can read it, so never put passwords, PAN or Aadhaar numbers in it. If you need confidentiality, that is JWE, a different format.

How verification goes wrong

Most JWT breaches come from verification mistakes, not cryptography:

  1. Accepting alg: none or letting the token choose the algorithm. Always pin allowed algorithms on the server, e.g. algorithms: ['RS256'].
  2. Algorithm confusion: a server expecting RS256 is tricked into verifying an HS256 token using the public key as the HMAC secret. Pinning the algorithm prevents it.
  3. Weak HS256 secrets that can be brute-forced offline. Use at least 256 bits of randomness.
  4. Not checking exp, aud, iss. A token minted for one service should not work on another.
  5. Using decode() instead of verify() in code paths. Decoding does no signature check.

Where to store it

StorageXSS can steal it?CSRF risk?Notes
localStorage / sessionStorageYes, any injected script can read itNoSimple, but one XSS means full token theft
JS memory (variable)Harder, lost on reloadNoPair with a refresh cookie
HttpOnly cookieNo, JS cannot read itYes, mitigate with SameSite and CSRF tokensRecommended default

An HttpOnly cookie does not make XSS harmless (an injected script can still make requests as the user while the page is open), but it stops the token from being exfiltrated and reused elsewhere. SameSite=Lax (the default in Chromium when unset) blocks most cross-site POSTs; Strict is tighter but breaks inbound links that need the session.

Revocation and the stateless trade-off

JWTs are attractive because the server can verify them without a database lookup. The cost is that you cannot easily revoke one before it expires. The common pattern is a short-lived access token (5 to 15 minutes) plus a long-lived refresh token stored server-side or in an HttpOnly cookie, rotated on every use. On logout or password change, revoke the refresh token; the access token dies soon after. For hard revocation, keep a denylist of jti values in Redis.

JWT login with cookie storage. The token never touches JavaScript; the browser attaches it automatically.
  1. Browser → Auth API: POST /login with credentials
  2. Auth API → Browser: Set-Cookie: access JWT (HttpOnly)
  3. Browser → Orders API: GET /orders, cookie attached
  4. Orders API → Orders API: Verify signature, exp, aud
  5. Orders API → Browser: 200 OK with user's orders

Code examples

Issuing and verifying a JWT safely (jsonwebtoken)

import jwt from 'jsonwebtoken';

// Issue: short expiry, explicit audience and issuer
const token = jwt.sign(
  { sub: user.id, role: user.role },
  process.env.JWT_SECRET,            // 32+ random bytes
  { algorithm: 'HS256', expiresIn: '15m', audience: 'orders-api', issuer: 'auth.example.in' }
);

res.cookie('access_token', token, {
  httpOnly: true,   // not readable by JS
  secure: true,     // HTTPS only
  sameSite: 'lax',
  maxAge: 15 * 60 * 1000,
});

// Verify: pin the algorithm and check claims
function requireAuth(req, res, next) {
  try {
    req.user = jwt.verify(req.cookies.access_token, process.env.JWT_SECRET, {
      algorithms: ['HS256'],
      audience: 'orders-api',
      issuer: 'auth.example.in',
    });
    next();
  } catch {
    res.sendStatus(401);
  }
}

Pinning `algorithms` blocks `alg: none` and algorithm-confusion tricks, and the cookie flags keep the token away from injected scripts.

Key points

  • JWT = header.payload.signature, each Base64URL encoded; the payload is readable by anyone.
  • Always verify with a pinned algorithm list and check exp, aud and iss.
  • HttpOnly cookies stop token theft via XSS but need SameSite or CSRF tokens.
  • Keep access tokens short-lived and use rotating refresh tokens for long sessions.
  • JWTs are hard to revoke; use a jti denylist if you need instant logout.

Common follow-up questions

  • How would you implement logout with stateless JWTs?
  • What is the difference between HS256 and RS256, and when would you pick each?
  • What is refresh token rotation and how does it detect token theft?
  • Would you use JWTs or server-side sessions for a simple monolith? Why?

Interview tips

  • Say clearly that a JWT is signed, not encrypted; many candidates get this wrong.
  • Explain the storage trade-off as XSS vs CSRF rather than declaring one option perfect.
  • Mentioning algorithm pinning and `alg: none` shows you understand real-world JWT bugs.

Concepts covered

JWT, JWS Signature, HttpOnly Cookie, Refresh Token, XSS, CSRF

More Web Security (OWASP, JWT, XSS, CSRF) questions