FullStack AI Hub
Studio
System Design · 07. Security
12 min
10 steps
Beginner

Authentication

Protect logins with Argon2id hashing, HttpOnly sessions, rotating tokens, and credential-stuffing limits.

System Design07. SecurityLesson 1 of 3
12 minBeginner10 steps

Authentication

Protect logins with Argon2id hashing, HttpOnly sessions, rotating tokens, and credential-stuffing limits.

Crack Rate
50B/s
8-Char Crack
< 4 min
Login Hash
0.001 ms
Breach Impact
Total Loss
POST /loginSELECT hashLeaked DumpLoginsAuth APIUsers DBAttackerGPUsBREACHCracked in minutesIdentical passwords = identical hashes
Login / Auth Request
Session / Token Issue
Verified Response
Credential Stuffing / Attack
Blocked / Revoked
In This LessonStep 1 of 10
What You Will Master
  • ✓Protect stored passwords with per-user salts and memory-hard Argon2id hashing
  • ✓Weigh stateful Redis session cookies against stateless JWTs and rotating refresh tokens
  • ✓Delegate login safely via OAuth 2.0 + OIDC PKCE and phishing-resistant Passkeys
  • ✓Defend login endpoints against botnet credential stuffing with layered rate limits

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Argon2id + 128-bit SaltStoring user passwords in your own credential databaseIntentionally uses ~64 MB RAM & 150–250 ms CPU per login to defeat GPU cracking
Opaque Session Cookie (Redis)Web apps requiring instant logout, device revocation, and minimal token sizeRequires a fast ~1 ms Redis lookup per authenticated request
Short JWT (15m) + Rotating RefreshMicroservices & mobile apps verifying identity locally via cached JWKSAccess tokens stay valid until expiry; refresh rotation requires reuse detection
Passkeys (WebAuthn) + OIDC PKCEEliminating password reuse and phishing across consumer and enterprise appsRequires account recovery flows when users lose all synced devices

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Authentication.

STEP 01 · PROBLEMJump to step →

Why Plaintext and Fast Hashes Fail

Storing passwords in plaintext—or hashing them with fast algorithms like **MD5** or **SHA-256**—turns any read-only SQL injection or leaked backup into a total account takeover.

Modern GPU rigs compute **50+ billion unsalted SHA-256 hashes per second**, cracking 90% of leaked human passwords in minutes and matching identical passwords via precomputed rainbow tables.

watch:Never use SHA-256, SHA-512, or MD5 for passwords—they were designed to be blazingly fast for file checksums, which makes brute-forcing trivial.

Rainbow TablesUnsalted HashGPU CrackingCredential Leak
STEP 02 · SOLUTIONJump to step →

Salted Argon2id Memory-Hard Hashing

**Argon2id** (winner of the Password Hashing Competition) combines two defenses: a unique random **128-bit salt** per user that destroys rainbow tables, plus **memory-hard** work (e.g., 64 MB RAM & ~200 ms CPU per hash) that neutralizes GPUs and ASICs.

Adding 200 ms to a legitimate login is invisible to a human typing their password, yet shrinks an attacker’s cracking speed from **50 billion/sec down to ~500/sec**—a 100,000,000× slowdown.

good:Store the algorithm, parameters, salt, and hash in one PHC string (`$argon2id$v=19$m=65536,t=3,p=1$...`) so you can seamlessly rehash users to stronger parameters on next login.

Argon2idPer-User SaltMemory-Hard KDFBcrypt / Scrypt
STEP 03 · TECHNIQUEJump to step →

Stateful Session Cookies in Redis

After verifying Argon2id once at login, the server generates a **256-bit cryptographically random Session ID**, stores `{userId, role, device, createdAt}` in **Redis**, and sets an **`HttpOnly; Secure; SameSite=Lax`** cookie.

`HttpOnly` blocks JavaScript (XSS) from reading the token, `Secure` restricts it to HTTPS, and `SameSite=Lax` stops cross-site CSRF form posts. Best of all, logging a user out globally is a single **`DEL session:<id>`** in Redis.

idea:Never store session state inside a single app server’s local RAM—horizontal scaling requires a shared Redis session store so any API instance can verify the cookie.

HttpOnly CookieSameSite=LaxRedis Session StoreInstant Revocation
STEP 04 · TECHNIQUEJump to step →

Stateless JWT Anatomy & Local JWKS Verification

A **JSON Web Token (JWT)** packs `header.payload.signature` directly inside the `Authorization: Bearer` header. The Auth server signs the claims (`sub`, `role`, `exp`) using an asymmetric private key (**EdDSA / RS256**).

Downstream microservices fetch the Auth server’s public keys once from `/.well-known/jwks.json` and verify signatures **locally in < 0.2 ms** with zero network calls to a central session store.

watch:JWT payloads are Base64URL-encoded, NOT encrypted! Anyone holding the token can decode the claims—never put secrets or sensitive PII inside a standard JWS.

JWT StructureJWKS Public KeysAsymmetric SigningStateless Verification
STEP 05 · TRADE-OFFJump to step →

The JWT Revocation Dilemma

Stateless JWTs carry a painful security catch: **you cannot revoke a valid JWT before its `exp` timestamp** without checking some shared state!

If an employee is terminated or a laptop is stolen while holding a 7-day JWT, microservices will keep honoring that token for 7 full days—unless you introduce a Redis denylist (which quietly turns your "stateless" JWT back into a stateful lookup).

watch:Never issue long-lived (24-hour or 7-day) stateless JWTs for sensitive actions like password changes, wire transfers, or admin panels.

Stateless RevocationToken DenylistExposure WindowSession Kill
STEP 06 · SOLUTIONJump to step →

Short Access JWT + Rotating Refresh Token

Production JWT systems get the best of both worlds with a **two-token pair**: a **short-lived Access JWT (5–15 min)** for zero-hop microservice verification, plus a **stateful Refresh Token (30 days)** stored hashed in the Auth DB and sent only to `/auth/refresh` in an `HttpOnly` cookie.

With **Refresh Token Rotation & Reuse Detection**, every refresh mints a brand-new pair and invalidates the old refresh token. If an attacker replays an already-spent refresh token, the server immediately revokes the entire **token family**!

good:Reuse detection turns a silent token theft into an immediate self-healing alarm: the moment either the victim or attacker reuses the stale refresh token, both sessions are nuked.

Access + Refresh PairToken RotationReuse DetectionToken Family
STEP 07 · TECHNIQUEJump to step →

OAuth 2.0 + OIDC with PKCE

Instead of handling passwords yourself, **OpenID Connect (OIDC)** built on **OAuth 2.0** lets users sign in via Google, GitHub, or Okta. The browser redirects to the Identity Provider (IdP) and returns with a one-time **Authorization Code**.

To stop malicious apps on mobile/SPAs from intercepting that code, **PKCE** (Proof Key for Code Exchange) hashes a client-generated secret (`code_verifier → code_challenge`) at login start; the IdP only swaps the code for an `id_token` if the backend/client presents the original `code_verifier`.

idea:Always pair OAuth redirects with a random `state` parameter (blocks login CSRF) and `PKCE` (blocks authorization code interception)—the legacy Implicit Flow is deprecated.

OAuth 2.0OpenID ConnectPKCE ChallengeState Parameter
STEP 08 · SOLUTIONJump to step →

Phishing-Resistant Passkeys (WebAuthn) & MFA

SMS OTPs and even TOTP 6-digit codes can be phished by real-time reverse proxies (`evil-login.com` relaying your code). **Passkeys (WebAuthn / FIDO2)** eliminate shared secrets entirely using public-key cryptography hardware-bound to the user’s device.

At login, the server sends a random **challenge nonce**. The browser automatically binds the signed response to the exact **TLS origin (`https://app.example.com`)**—so a phishing domain gets a signature rejection every single time.

good:Offer Passkeys first for zero-phishing UX, keep TOTP authenticator apps as a universal MFA fallback, and avoid SMS OTP for high-value accounts (SIM-swapping risk).

WebAuthn / FIDO2PasskeysOrigin BindingTOTP MFA
STEP 09 · PROBLEMJump to step →

Defending Against Credential Stuffing Waves

Attackers buy billions of `(email, password)` pairs leaked from other sites and replay them across **100,000 residential proxy IPs** against your `/login` endpoint. Simple per-IP rate limits miss low-and-slow botnets, while rigid account lockouts let attackers DoS your real customers.

Production defense layers **multi-dimensional rate limits** (per IP subnet, per account identifier, and global velocity), **breached-password checks** (k-anonymity HaveIBeenPwned), and **progressive step-up challenges** (Turnstile / MFA) only on anomalous signals.

watch:Always return uniform error messages ("Invalid email or password") and constant-time dummy Argon2id work on unknown emails to prevent attackers from enumerating valid accounts.

Credential StuffingAccount EnumerationMulti-Key Rate LimitStep-Up MFA
STEP 10 · RECAPJump to step →

Production Authentication Blueprint

Great authentication layers simple, battle-tested primitives: **Edge stuffing rate limits** in front, **Passkeys / OIDC PKCE** first, **salted Argon2id** for passwords, and either **HttpOnly Redis sessions** (web apps) or **15m Access JWT + Rotating Refresh** (APIs & mobile).

Never roll your own cryptography, always separate identity issuance from microservice verification, and build instant session/family revocation into day one.

good:Default rule of thumb: browser apps → HttpOnly Redis Session Cookie; multi-service / mobile APIs → 15-min Access JWT + Rotating Refresh Token + Passkey/OIDC.

Defense-in-Depth AuthArgon2idHttpOnly + SameSitePasskeys + Rotation

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.