Chapter 6 of 8
Course Progress0 of 8 completed (0%)

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.

Passwords, Tokens & Secure LoginDesign 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.UNDERSTANDPasswordsFOLLOW THE FLOWTokensAPPLY ITSecure LoginPasswords, Tokens & Secure LoginDesign 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.UNDERSTANDPasswordsFOLLOW THE FLOWTokensAPPLY ITSecure Login

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.

Concept Check

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

jwt.sign({ ssn: "123-45-6789" }) → atob(payload) = Plaintext Leaked!Base64Url encoding is NOT encryption; anyone can decode it instantly

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

Header + Payload + HMAC(secret) → Tampering Detected in Constant TimeGuarantees authenticity and provenance; keep sensitive secrets on the server

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;
  }
}
Concept Check

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

STATUS: 200 OK (VERIFIED)
Serialized Wire Token (Header.Payload.Signature):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c3JfODgyNDEiLCJ1c2VybmFtZSI6ImFsZXhfZGV2Iiwicm9sZSI6Im1lbWJlciIsImV4cCI6MTc3MzAwMDAwMH0=.28b79c88a7f2
Header (Algorithm) Payload (Claims) Signature (HMAC)
Client Request TokenAuthorization: Bearer ...alg: "HS256"role: "member" sig: 28b79c88a7...Server HMAC VerificationCompute expected signatureHMAC(header.payload, key)Expected: 28b79c88a7...Signatures Match ✓Authentication GateACCESS GRANTEDIdentity verified. Key signed.User: alex_dev (member)
Cryptographic Integrity Proof:

Signature verified! The token is completely valid, untampered, and unexpired.

Concept Check

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:

JWT Authentication Hardening · Replace Decode with Verify
JavaScript

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Replace jwt.decode(token) with jwt.verify(token, JWT_SECRET, options).
  • Pass JWT_SECRET as 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'] (or RS256) during verification to permanently block algorithm substitution attacks.

Ready for Chapter 7? Mark this chapter as complete to proceed to Secrets & Supply Chain Safety:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us