Cybersecurity Essentials for Developers · Chapter 6 · ~15 min · Advanced
Passwords, Tokens & Secure Login
Design resilient authentication systems. Understand stateful session cookies vs stateless JSON Web Tokens (JWT), prevent signature bypass vulnerabilities like the infamous 'alg: none' flaw, and implement secure refresh token rotation with automated reuse detection.
- Compare stateful server-side sessions vs stateless signed JWT tokens
- Dissect JWT anatomy (Header, Payload, Signature) and prevent the 'none' algorithm flaw
- Implement secure Refresh Token Rotation with automatic reuse detection
- Simulate JWT signing, tamper verification, and token expiration in an interactive visualizer
Passwords, Tokens & Secure Login: learn it visually
Design resilient authentication systems. Understand stateful session cookies vs stateless JSON Web Tokens (JWT), prevent signature bypass vulnerabilities like the infamous 'alg: none' flaw, and implement secure refresh token rotation with automated reuse detection.
1Everyday Intuition: The Coat Check vs The VIP Festival Wristband
In modern web development, there are two primary paradigms for keeping users logged in:
Stateful Session: The Coat-Check Claim Ticket
When you check your coat, the attendant hands you a tiny ticket stamped with only a number: #412. The attendant must look up #412 in a giant internal ledger book (Redis or SQL) to see which jacket belongs to you. If the ledger is lost or the database goes down, nobody can prove what they own.
Stateless JWT: The Holographic Event Wristband
When you enter a festival, you receive a tamper-evident wristband printed with your name, VIP tier, and expiration timestamp. Every stage bouncer can inspect the holographic security seal (cryptographic signature) to verify your access instantly, without having to radio central headquarters on every entry.
What is the primary architectural tradeoff when choosing stateless JWTs over stateful server sessions?
2Architecture & Code Mechanics: JWT Anatomy & Safe Verification
A JSON Web Token consists of three base64url-encoded parts separated by periods: header.payload.signature.
Wrong idea: JWT Base64 Payloads Are Encrypted and Confidential
Assuming that because a JSON Web Token looks like an unreadable string of random characters (`eyJhbGciOiJIUzI1Ni...`), the payload is encrypted and secrets can be safely stored inside.
Real system: JWTs Are Cryptographically Signed for Integrity, Not Secrecy
A standard JWT provides tamper-proofing via a digital signature. Anyone who intercepts the token can read the claims, but nobody can alter a single character without invalidating the cryptographic signature.
Production JWT Issuance & Verification (Node.js & TypeScript)
Always enforce short access token lifespans (15 minutes), explicit algorithm whitelisting, and store refresh tokens in secure HttpOnly cookies:
import jwt from "jsonwebtoken";
const ACCESS_SECRET = process.env.JWT_ACCESS_SECRET!;
// 1. Issue short-lived access token (15m expiration)
export function generateAccessToken(userId: string, role: string) {
return jwt.sign(
{ sub: userId, role: role },
ACCESS_SECRET,
{ algorithm: "HS256", expiresIn: "15m" }
);
}
// 2. Cryptographic verification with strict algorithm whitelisting
export function verifyAccessToken(token: string) {
try {
return jwt.verify(token, ACCESS_SECRET, {
algorithms: ["HS256"], // Critical: defeats 'alg: none' bypass!
});
} catch (err) {
// Throws TokenExpiredError or JsonWebTokenError
return null;
}
}How does Refresh Token Rotation with automatic reuse detection protect against credential theft?
3Interactive Visual Simulation: JWT Cryptographic Tamper Visualizer
Experiment with how HMAC signatures detect tampering. Try elevating your role fromMember to Admin or altering the server secret key:
Interactive JWT Cryptographic Tamper Visualizer
Signature verified! The token is completely valid, untampered, and unexpired.
Why did the famous 'alg: none' JWT vulnerability allow unauthorized administrative access in older web applications?
4Hands-On Challenge: Fix Insecure JWT Middleware
A developer implemented JWT authentication using jwt.decode() instead of jwt.verify(), allowing anyone to craft arbitrary base64 strings and bypass login security completely. Harden the middleware and run verification:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Replace
jwt.decode(token)withjwt.verify(token, JWT_SECRET, options). - Pass
JWT_SECRETas the second argument to verify the signature. - Enforce the algorithm whitelist by passing
{ algorithms: ['HS256'] }as options.
5Architecture Recap & Next Steps
- Signing vs. Encryption: Standard JWTs are signed for integrity, not encrypted. Never store unencrypted secrets or sensitive PII in token payloads.
- Short-Lived Access: Keep access tokens short-lived (10–15 minutes) to contain the blast radius if an individual token is intercepted.
- Refresh Token Rotation: Issue single-use refresh tokens stored in HttpOnly cookies with automatic reuse detection.
- Enforce Whitelists: Always specify
algorithms: ['HS256'](orRS256) during verification to permanently block algorithm substitution attacks.
Ready for Chapter 7? Mark this chapter as complete to proceed to Secrets & Supply Chain Safety: