The Challenge-Response Flow
HTTP has a built-in authentication framework based on challenge-response. When a client requests a protected resource, the server responds with 401 Unauthorized and a WWW-Authenticate header that tells the client how to authenticate.
── Request (no credentials) ────────────────────────
GET /api/admin HTTP/1.1
Host: example.com
── Response (challenge) ────────────────────────────
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Admin Area"
── Request (with credentials) ──────────────────────
GET /api/admin HTTP/1.1
Host: example.com
Authorization: Basic dXNlcjpwYXNzd29yZA==
── Response (authorized) ───────────────────────────
HTTP/1.1 200 OK
Content-Type: application/json
{"admin": true, "users": [...]}
Authentication Methods Compared
| Method | How It Works | Pros | Cons |
|---|---|---|---|
| Basic Auth | Base64-encoded username:password in every request |
Simple, built into HTTP, supported everywhere | Credentials sent with every request; base64 is encoding, not encryption |
| Bearer Token / JWT | Token in Authorization: Bearer <token> header |
Stateless, scalable, can contain user data (JWT) | Token management (expiration, revocation), size can be large |
| API Key | Key in header (X-API-Key), query param, or cookie |
Simple, easy to provision and revoke | No standard; if in query string, visible in logs |
| Cookie Session | Session ID in cookie; server stores session data | Browser handles automatically, HttpOnly for security | Requires server-side state, vulnerable to CSRF without SameSite |
Cookie Sessions vs Token-Based Auth
| Aspect | Cookie Sessions | Token-Based (JWT) |
|---|---|---|
| State | Server stores session data | Token contains all data (stateless) |
| Sent how | Automatically by browser (Cookie header) | Manually in code (Authorization header) |
| Cross-domain | Complex (CORS + SameSite issues) | Easy (just include the header) |
| Revocation | Easy (delete session from server) | Harder (token is valid until it expires) |
| Best for | Traditional web apps (server-rendered) | APIs, SPAs, mobile apps, microservices |