JWT Security
Critical JWT vulnerabilities — the 'none' algorithm attack, weak secrets, missing expiry — and how to implement tokens safely
Skills taught: websecurity.jwt, websecurity.jwt-none-attack, websecurity.jwt-algorithm-confusion, websecurity.jwt-expiry, websecurity.refresh-tokens
JWT structure and common vulnerabilities
A JWT has three base64url-encoded parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ← HEADER
.eyJ1c2VySWQiOiIxMjMiLCJyb2xlIjoidXNlciIsImV4cCI6MTcwMDAwMDAwMH0 ← PAYLOAD
.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ← SIGNATURE
Decoded header: { "alg": "HS256", "typ": "JWT" }
Decoded payload: { "userId": "123", "role": "user", "exp": 1700000000 }
The SIGNATURE is computed by the server:
HMACSHA256(base64url(header) + '.' + base64url(payload), secret)
The payload is NOT encrypted — anyone can decode it (base64 is encoding, not encryption).
The signature prevents TAMPERING — you can't change the payload without invalidating the signature
(unless the secret is weak, or the server accepts 'none' as the algorithm).
DO store in JWT: userId, role, sessionId, expiry (exp), issued-at (iat)
DO NOT store in JWT: passwords, credit card numbers, PII, secrets
(the payload is readable by anyone who has the token)
The 'none' algorithm attack
// THE ATTACK:
// Early JWT libraries allowed the 'alg' header field to be 'none'
// meaning: 'no signature verification needed'
// An attacker could:
// 1. Decode any JWT (they're just base64)
// 2. Modify the payload: change role: 'user' → role: 'admin'
// 3. Change the header: alg: 'HS256' → alg: 'none'
// 4. Remove the signature part (or leave it empty)
// 5. Submit the forged token — vulnerable servers would accept it!
// Forged token example:
// Header: { "alg": "none" }
// Payload: { "userId": "123", "role": "admin" } ← escalated role
// Signature: (empty)
// THE FIX — always specify allowed algorithms explicitly:
import jwt from 'jsonwebtoken'; // npm install jsonwebtoken
const JWT_SECRET = process.env.JWT_SECRET!; // Must be strong random string
// SIGNING — specify algorithm explicitly
function issueToken(userId: string, role: string): string {
return jwt.sign(
{ userId, role },
JWT_SECRET,
{
algorithm: 'HS256', // Always explicit
expiresIn: '15m', // Short expiry — use refresh tokens for longer sessions
issuer: 'myapp.com',
audience: 'myapp.com',
}
);
}
// VERIFICATION — explicitly reject 'none' and other algorithms you don't use
function verifyToken(token: string) {
return jwt.verify(token, JWT_SECRET, {
algorithms: ['HS256'], // CRITICAL: only accept HS256 — rejects 'none', RS256, etc.
issuer: 'myapp.com',
audience: 'myapp.com',
});
// jwt.verify throws JsonWebTokenError if the token is invalid
// jwt.verify throws TokenExpiredError if the token has expired
}
Algorithm confusion — HS256 vs RS256
// BACKGROUND:
// HS256 uses a SYMMETRIC secret (same secret to sign and verify)
// RS256 uses ASYMMETRIC keys (private key to sign, PUBLIC key to verify)
// ALGORITHM CONFUSION ATTACK:
// Imagine a server that uses RS256 (public/private key pair)
// The server's PUBLIC key is... public. Anyone can read it.
// If the server accepts both RS256 and HS256:
// 1. Attacker takes the server's public key
// 2. Creates a new HS256 token signed with the PUBLIC key as the HMAC secret
// 3. Server tries to verify HS256... using what secret?
// If it uses the PUBLIC key as the HS256 secret, the token verifies!
// THE FIX — never mix symmetric and asymmetric in the same system:
// If you use HS256 (symmetric — simpler, good for single-service auth):
const secret = process.env.JWT_SECRET!; // Must be a strong random 256-bit value
// Generation: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
jwt.verify(token, secret, { algorithms: ['HS256'] });
// If you use RS256 (asymmetric — better for multi-service, public key verification):
import { readFileSync } from 'fs';
const privateKey = readFileSync('private.pem');
const publicKey = readFileSync('public.pem');
// Sign with private key:
jwt.sign(payload, privateKey, { algorithm: 'RS256' });
// Verify with public key ONLY:
jwt.verify(token, publicKey, { algorithms: ['RS256'] }); // NOT ['RS256', 'HS256']
// KEY RULE: never accept multiple algorithm families in the same verify call
// SHORT-LIVED ACCESS TOKEN (15 minutes) + LONG-LIVED REFRESH TOKEN (7 days)
// Access tokens can't be revoked (stateless), so keep them short
// Refresh tokens are stored server-side — they CAN be revoked
// On login:
async function login(email: string, password: string, res: Response) {
const user = await verifyCredentials(email, password);
// Short-lived access token — stateless, no DB lookup needed
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_ACCESS_SECRET!,
{ expiresIn: '15m', algorithm: 'HS256' }
);
// Long-lived refresh token — stored in DB for revocation
const refreshToken = crypto.randomBytes(40).toString('hex');
await db.refreshTokens.create({
token: refreshToken,
userId: user.id,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
});
// Access token: in response body (SPA reads it)
// Refresh token: in HttpOnly cookie (JS can't read it)
res.cookie('refreshToken', refreshToken, {
httpOnly: true, secure: true, sameSite: 'lax',
maxAge: 7 * 24 * 60 * 60 * 1000,
});
return { accessToken }; // Client stores in memory, NOT localStorage
}
// Refresh endpoint — called when access token expires
async function refresh(req: Request, res: Response) {
const refreshToken = req.cookies.refreshToken;
const stored = await db.refreshTokens.findOne({ token: refreshToken });
if (!stored || stored.expiresAt < new Date()) {
return res.status(401).json({ error: 'Please log in again' });
}
const user = await db.users.findById(stored.userId);
const newAccessToken = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_ACCESS_SECRET!,
{ expiresIn: '15m', algorithm: 'HS256' }
);
return res.json({ accessToken: newAccessToken });
}
Frequently Asked Questions
Should I store JWTs in localStorage or cookies?
Cookies (HttpOnly) for the refresh token; memory (React state) for the short-lived access token. Never localStorage for long-lived tokens. localStorage is accessible to any JavaScript on your page — a single XSS vulnerability can steal every stored token. HttpOnly cookies can't be read by JavaScript. Memory is safest but tokens are lost on page refresh, which is why the refresh token (in HttpOnly cookie) is used to re-issue a new access token automatically. This is the recommended pattern.