17. Authentication & Authorization
Big picture: Every system must answer two questions on every sensitive request: Who are you? (authentication) and What are you allowed to do? (authorization). Get auth wrong and you leak data, double-charge users, or lock out legitimate customers.
Lesson 04 and lesson 15 introduced auth at a glance. This lesson goes deep โ sessions vs JWT, OAuth, RBAC, where checks live in an HLD, and the mistakes interviewers watch for.
Prerequisites: 04. Clients, Servers & APIs, 10. Caching (session store), 15. Reliability, Security & Observability
Read next: 18. Transactions & Isolation โ then 19. Single Sign-On for enterprise federation.
Learning goals
By the end of this lesson you will be able to:
- Distinguish authentication (authn) from authorization (authz) and map each to HTTP status codes
- Compare session cookies, JWTs, API keys, and OAuth 2.0 / OIDC
- Explain a "Sign in with Google" flow at interview depth
- Choose RBAC, ownership checks, and ACLs for common product scenarios
- Place auth gateway / auth service correctly in an HLD
- Describe service-to-service auth (mTLS, internal tokens)
- Avoid classic mistakes (trusting client
user_id, long-lived tokens everywhere)
Authn vs authz โ the two questions
| Term | Question | Pass | Fail (HTTP) |
|---|---|---|---|
| Authentication (authn) | Who are you? | Valid session, JWT, API key | 401 Unauthorized โ identity unknown or expired |
| Authorization (authz) | What may you do? | Role, ownership, policy allows action | 403 Forbidden โ we know who you are, but not allowed |
Request: DELETE /api/v1/posts/99
Authorization: Bearer eyJ... (user_id = 42)
Authn: Verify signature + expiry โ user 42 is authenticated โ
Authz: Is user 42 the owner of post 99? โ no โ 403 Forbidden
Building analogy: Authn = showing ID at the lobby. Authz = your badge opens certain floors โ identification alone doesn't grant access.
Interview phrase: "We authenticate on every request at the API layer, then authorize per resource โ owner or admin can delete; others get 403."
Where auth happens in the request path
| Layer | Typical authn job | Typical authz job |
|---|---|---|
| CDN / edge | Signed URLs for private media | Time-limited access to object |
| API gateway | JWT validation, API key lookup | Coarse RBAC (/admin/* needs admin) |
| App service | Re-validate or trust gateway identity | Resource ownership (post owner, order buyer) |
| Database | Connection credentials (IAM) | Row-level security (advanced) |
Golden rule: Never trust user_id from the request body or query string. Derive identity from a validated token server-side.
Authentication mechanisms
Five common ways to prove identity โ pick by client type and trust boundary.
| Mechanism | Typical client | Remember |
|---|---|---|
| Session cookie | Web app | Server session in Redis; HttpOnly cookie |
| JWT | Mobile, SPA, microservices | Signed token; short TTL + refresh |
| OAuth / OIDC | Social login | Code exchange on your backend |
| API key | Scripts, partners | Rate limit + scoped permissions |
| mTLS | Service mesh | Certs on east-west traffic |
Session cookies (server-side session)
| Pros | Cons |
|---|---|
| Easy logout (delete session server-side) | Needs shared session store at scale (Redis) |
| Short cookie โ less leaked data | CSRF protections needed for cookie-based writes |
| Familiar for traditional web apps | Harder for native mobile unless cookie jar |
Scale note: Avoid sticky sessions as the primary strategy โ store sessions in Redis so any app server can validate.
JWT (JSON Web Token)
Self-contained token: header + payload + signature. Server verifies signature with a secret or public key.
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Payload (example):
{
"sub": "42",
"email": "user@example.com",
"roles": ["user"],
"exp": 1735689600
}
| Pros | Cons |
|---|---|
| Stateless verification โ no DB hit every request | Hard to revoke instantly (need blocklist or short TTL) |
| Works well for mobile + SPA + microservices | Payload is signed, not encrypted โ don't put secrets in JWT |
| Easy to pass between services | Token theft = bearer has access until expiry |
Patterns:
| Pattern | When |
|---|---|
| Short-lived access JWT (15 min) + refresh token (HTTP-only cookie or secure store) | Most user-facing apps |
| Long-lived API JWT for internal services | Only with mTLS + network isolation |
| Asymmetric keys (RS256) | Auth service signs; other services verify with public key |
API keys
X-API-Key: sk_live_abc123
| Best for | Not for |
|---|---|
| Developer / partner APIs | End-user login in a mobile app |
| Server-to-server with rate limits | Fine-grained per-resource authz alone |
Pair API keys with rate limiting (lesson 15) and scoped permissions (read-only vs write).
OAuth 2.0 and OpenID Connect (OIDC)
OAuth 2.0 = authorization framework ("app X may access my Google calendar").
OIDC = identity layer on OAuth ("here is who the user is" โ ID token).
"Sign in with Google" (authorization code flow โ most common for web):
| Concept | Meaning |
|---|---|
| Authorization code | One-time code exchanged server-side โ secret never in browser |
| ID token (OIDC) | Claims about user (sub, email, name) |
| Access token | Call Google APIs on user's behalf |
| Your app's session/JWT | What your API checks on /feed, /checkout, etc. |
Interview phrase: "Social login uses OAuth authorization code flow; our backend exchanges the code and issues our own short-lived JWT โ we don't trust the Google access token for our internal APIs."
Enterprise scale: 19. Single Sign-On โ IdP vs SP, SAML, OIDC SSO, B2B federation, and multi-app architecture.
mTLS and service-to-service auth
User JWTs don't belong on every internal hop. At scale:
| Pattern | Use |
|---|---|
| mTLS | Both client and server present TLS certificates |
| Internal signed token | Gateway mints service token after user authn |
| Workload identity | K8s service account โ cloud IAM role |
Interview phrase: "Edge validates user JWT; east-west traffic uses mTLS between services in the mesh."
Authorization models
Authentication tells you user_id = 42. Authorization decides what 42 can do.
Role-Based Access Control (RBAC)
Permissions attached to roles; users get roles.
roles:
user โ create_post, read_feed
admin โ delete_any_post, ban_user
support โ read_order, issue_refund (limited)
| Good for | Weak when |
|---|---|
| Admin panels, coarse features | "User 42 can edit doc 7 but not doc 8" โ needs resource rules too |
Resource ownership (object-level)
Most product APIs combine RBAC + ownership:
DELETE /posts/99
if JWT.roles contains admin โ allow
else if post.owner_id == JWT.sub โ allow
else โ 403
Always load owner from DB (or cache) โ don't trust client-sent owner_id.
Access Control Lists (ACLs)
Explicit list per resource: "doc 7: [alice: read, bob: edit]". Common in collaboration products (Google Docs-style sharing).
Attribute-Based Access Control (ABAC)
Policy engine evaluates attributes: user department, resource classification, time of day. Powerful at enterprise scale; heavier to explain in a 45-minute interview unless the prompt is healthcare or banking.
Decision table โ pick a model
| Scenario | Model |
|---|---|
| Instagram-style posts | Ownership + admin role |
| Company admin dashboard | RBAC |
| Shared document editor | ACL per document |
| "Analysts read PII only in business hours" | ABAC (awareness) |
Tokens, cookies, and browser security (awareness)
Full web security is in lesson 15. Auth-specific highlights:
| Control | Protects against |
|---|---|
| HTTPS / TLS | Token interception on the wire |
| HttpOnly cookie | JavaScript stealing session cookie (XSS) |
| SameSite=Lax/Strict | Cross-site request forgery on cookies |
| CSRF token | Forged state-changing requests with session cookie |
| CORS | Untrusted origins calling your API from browsers |
| Short TTL + refresh | Stolen JWT window of abuse |
| Mistake | Better |
|---|---|
JWT in localStorage for high-risk apps | HttpOnly cookie or secure native keystore |
| Never rotate refresh tokens | Rotation on use; revoke family on theft |
| Log full JWT in application logs | Log sub / request id only |
Passwords and credentials (brief)
Even with OAuth, many apps still have email/password.
| Rule | Why |
|---|---|
| Store hashes only (bcrypt, Argon2) | DB leak doesn't expose plaintext passwords |
Rate-limit /login | Brute-force protection |
| MFA for admin / payments | Stolen password isn't enough |
| Never send passwords in URLs | Logs and referrer leaks |
OAuth doesn't remove your obligation to protect your account database if you offer local signup.
Worked example โ photo sharing app
Requirements:
- Public profiles readable without login
- Upload / delete only own photos
- Moderators can remove any photo
- Mobile app + web SPA
HLD auth choices:
Authn:
- OAuth (Google, Apple) + optional email/password
- After login, issue access JWT (15 min) + refresh token (7 d, rotatable)
- Session metadata in Redis for logout / revoke
Authz:
- GET /users/{id}/photos โ public (no authn) or optional auth for private accounts
- POST /photos โ authn required; owner_id = JWT.sub
- DELETE /photos/{id} โ owner OR role=moderator
- POST /admin/ban โ role=admin only (gateway + app double-check)
Storage:
- Private originals in object storage; CDN serves signed URLs after authz check
Narration for interview: "Gateway validates JWT and attaches user id. Photos service enforces ownership on writes. Moderation uses RBAC. Reads of private media go through signed URLs after we check follow relationship."
Service accounts, bots, and machine users
Not every caller is a human.
| Caller | Authn pattern |
|---|---|
| Cron job exporting reports | API key or workload IAM role |
| Payment webhook from Stripe | Verify signature with shared secret |
| Mobile app | User JWT |
| Internal ledger service | mTLS + internal service identity |
Separate human sessions from machine credentials in design docs โ different rotation and blast radius.
Auth in your HLD checklist
When drawing lesson 20 diagrams, explicitly mark:
- Which endpoints are public vs authenticated
- Where JWT/session is validated (gateway vs each service)
- Where authz runs (ownership, roles)
- Session/token store (Redis, auth DB)
- OAuth identity provider if social login
- Rate limits on login and write APIs
- Audit log for admin and payment actions
- Fail closed vs fail open decision for authz edge cases
| Question | Example answer |
|---|---|
| Fail closed or open if auth service down? | Closed for payments; read-only public feed may stay open |
| Guest checkout? | Optional authn; authz on order tied to email link token |
| Multi-tenant SaaS? | Every query scoped by tenant_id from JWT โ never from client body alone |
Check your understanding
1. User is logged in but gets 403 on DELETE /orders/555. What failed?
Authentication succeeded (otherwise 401). Authorization failed โ user 555 isn't theirs, order is final, or role lacks refund permission. Check ownership and RBAC rules.
2. Why exchange OAuth authorization code on the server, not in the browser?
The exchange requires client_secret. Server-side exchange keeps secrets off the device and reduces risk of stolen codes being swapped for tokens by malicious JS.
3. JWT says user_id=42. Why still query DB before DELETE?
Authz is resource-specific. JWT proves identity and maybe roles; it doesn't prove user 42 owns post 99. Ownership can change (transfer, moderation). Always verify against authoritative data.
4. Session cookie vs JWT โ when prefer each?
Session cookie + Redis: traditional web, easy revoke, HttpOnly CSRF-aware setup. JWT: mobile/SPA/microservices, stateless verification, short TTL + refresh. Many production systems use both patterns in different clients.
Common beginner mistakes
| Mistake | Better |
|---|---|
Trust user_id from JSON body | Derive from validated token only |
| Auth only at gateway, never in service | Defense in depth โ services enforce authz |
| 401 vs 403 swapped | 401 = not identified; 403 = identified but denied |
One global isAdmin flag in JWT for everything | RBAC + resource checks; minimal claims in token |
| OAuth access token passed to every microservice | Issue your internal identity token |
| No logout story with JWT | Short TTL, refresh rotation, blocklist for high-risk |
| Public S3 + secret URL | Private bucket + signed URL after authz (lesson 13) |
Skip rate limits on /login | Lockout, CAPTCHA, exponential backoff |
Recap
- Authn = who; Authz = what they may do โ 401 vs 403.
- Sessions (Redis) vs JWT (stateless) โ pick by client type and revoke needs.
- OAuth/OIDC for social login; backend exchanges code and issues your tokens.
- RBAC + ownership covers most consumer app authz.
- Validate at gateway; enforce resource authz in the service that owns the data.
- mTLS / service identity for east-west traffic; user JWT at the edge.
- Never trust client-supplied identity fields.
Previous: 16. Retries, Timeouts & Resilience
Next: 18. Transactions & Isolation