Difficulty: Intermediate
What is a JWT, how is it structured and verified, and where should you store it safely in a browser?
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.
{"alg":"HS256","typ":"JWT"}.sub (user id), exp (expiry), iat (issued at), iss (issuer), aud (audience) and custom ones like role.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.
Most JWT breaches come from verification mistakes, not cryptography:
alg: none or letting the token choose the algorithm. Always pin allowed algorithms on the server, e.g. algorithms: ['RS256'].exp, aud, iss. A token minted for one service should not work on another.decode() instead of verify() in code paths. Decoding does no signature check.| Storage | XSS can steal it? | CSRF risk? | Notes |
|---|---|---|---|
localStorage / sessionStorage | Yes, any injected script can read it | No | Simple, but one XSS means full token theft |
| JS memory (variable) | Harder, lost on reload | No | Pair with a refresh cookie |
HttpOnly cookie | No, JS cannot read it | Yes, mitigate with SameSite and CSRF tokens | Recommended 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.
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.
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.
JWT, JWS Signature, HttpOnly Cookie, Refresh Token, XSS, CSRF