๐๏ธ Token-Based Authentication (JWT & OAuth)
How modern web apps stay logged in without re-sending passwordsโฑ ~3 min
The Session Problem
HTTP is stateless โ each request is independent. After you log in, the server needs a way to know that subsequent requests come from you without requiring your password on every request. Two approaches exist: server-side sessions (server stores a session object and gives you a session ID cookie) or token-based auth (server issues a cryptographically signed token you send with every request).
JWT โ JSON Web Tokens
A JWT is a compact, URL-safe token with three base64url-encoded parts separated by dots: header.payload.signature.
// Header (base64url decoded){ "alg": "RS256", "typ": "JWT" } // Payload (base64url decoded) โ the claims{ "sub": "user_123", "email": "alice@example.com", "roles": ["user", "admin"], "iat": 1704067200, // issued at "exp": 1704070800 // expires at (1 hour later)} // Signature: RS256(base64(header) + '.' + base64(payload), private_key)// Verification: verify signature with public key; check exp not in the pastOAuth 2.0 โ Delegated Authorization
OAuth 2.0 is an authorization framework that lets you grant a third-party application limited access to your account without giving it your password. 'Sign in with Google' is OAuth 2.0 โ you authenticate to Google, Google issues a token that the app can use to access only the specific data you authorized (email, profile), and your Google password is never shared with the app.
| Role | Who It Is | Example |
|---|---|---|
| Resource Owner | The user | You |
| Client | Third-party app requesting access | Spotify wanting your Google account |
| Authorization Server | Issues tokens after user consent | Google's OAuth server |
| Resource Server | API holding protected data | Google People API (your contacts) |
The JWT 'alg: none' attack works when a serverโฆ