Authentication: Sessions, JWT, OAuth2, SSO

Authentication Methods

MethodHowBest For
Session + CookieServer stores session, client gets session ID cookieTraditional web apps
JWT (JSON Web Token)Signed token containing claims, statelessAPIs, microservices, mobile
OAuth2Delegated authorization (login with Google/GitHub)Third-party access
API KeyStatic secret key per clientServer-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