Authentication: Sessions, JWT, OAuth2, SSO
Authentication Methods
| Method | How | Best For |
|---|---|---|
| Session + Cookie | Server stores session, client gets session ID cookie | Traditional web apps |
| JWT (JSON Web Token) | Signed token containing claims, stateless | APIs, microservices, mobile |
| OAuth2 | Delegated authorization (login with Google/GitHub) | Third-party access |
| API Key | Static secret key per client | Server-to-server, simple APIs |
JWT Structure
// Three parts: header.payload.signature (base64 encoded)
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjMsImV4cCI6MTcwOTAwMH0.signature
// Payload (decoded):
{ "user_id": 123, "role": "admin", "exp": 1709000000 }
// Server verifies signature without DB lookup (stateless!)
// Trade-off: can't revoke until expiry (use short TTL + refresh tokens)
OAuth2 Flow (Simplified)
1. User clicks "Login with Google"
2. App redirects to Google login page
3. User authenticates with Google
4. Google redirects back with authorization code
5. App exchanges code for access token (server-to-server)
6. App uses token to get user info from Google
7. App creates local session/JWT for the user
Microservice Auth Pattern
Client ──JWT──► API Gateway (validates JWT signature)
│ (adds user context to headers)
▼
Internal services trust the gateway
(no re-validation needed internally)
Key Takeaways
- JWT: stateless, scalable, but hard to revoke (use short TTL)
- Sessions: stateful, easy to revoke, needs shared session store at scale
- OAuth2: for "login with X" and third-party API access
- API Gateway validates auth once, internal services trust it