Stage 3 · Build
Authentication & Authorization
JWT Authentication
Issue and verify JWTs with claims, expiry, signing keys, refresh tokens, and revocation lists.
What Are JWTs
JSON Web Tokens are self-contained tokens that carry user claims. Unlike sessions, JWTs are stateless — the server verifies them without a database lookup. This makes them ideal for distributed systems and APIs.
JWT Structure
A JWT has three parts: header, payload, and signature. The header specifies the algorithm. The payload contains claims (user ID, role, expiry). The signature proves the token was issued by your server and has not been tampered with.
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTIzIiwicm9sZSI6ImFkbWluIiwiZXhwIjoxNzAwMDAwMDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cEach part is base64url-encoded. The header and payload are not encrypted — they are readable by anyone. The signature prevents tampering. Never put secrets in the payload.
Issuing JWTs
Verifying JWTs
Refresh Tokens
Access tokens expire quickly (15 minutes). Refresh tokens live longer (7 days) and are used to get new access tokens without re-authenticating. Store refresh tokens server-side for revocation capability.
Revocation
JWTs are stateless — they are valid until they expire. To revoke a JWT before expiry, you need a revocation list. Store revoked token IDs in Redis with the token's remaining TTL.
JWTs are best for distributed APIs where sessions are impractical. Sessions are simpler, support instant revocation, and do not need token rotation. For web applications with a single backend, sessions are usually the better choice.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.