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

TermQuestionPassFail (HTTP)
Authentication (authn)Who are you?Valid session, JWT, API key401 Unauthorized โ€” identity unknown or expired
Authorization (authz)What may you do?Role, ownership, policy allows action403 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

LayerTypical authn jobTypical authz job
CDN / edgeSigned URLs for private mediaTime-limited access to object
API gatewayJWT validation, API key lookupCoarse RBAC (/admin/* needs admin)
App serviceRe-validate or trust gateway identityResource ownership (post owner, order buyer)
DatabaseConnection 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.

MechanismTypical clientRemember
Session cookieWeb appServer session in Redis; HttpOnly cookie
JWTMobile, SPA, microservicesSigned token; short TTL + refresh
OAuth / OIDCSocial loginCode exchange on your backend
API keyScripts, partnersRate limit + scoped permissions
mTLSService meshCerts on east-west traffic

Session cookies (server-side session)

ProsCons
Easy logout (delete session server-side)Needs shared session store at scale (Redis)
Short cookie โ€” less leaked dataCSRF protections needed for cookie-based writes
Familiar for traditional web appsHarder 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
}
ProsCons
Stateless verification โ€” no DB hit every requestHard to revoke instantly (need blocklist or short TTL)
Works well for mobile + SPA + microservicesPayload is signed, not encrypted โ€” don't put secrets in JWT
Easy to pass between servicesToken theft = bearer has access until expiry

Patterns:

PatternWhen
Short-lived access JWT (15 min) + refresh token (HTTP-only cookie or secure store)Most user-facing apps
Long-lived API JWT for internal servicesOnly 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 forNot for
Developer / partner APIsEnd-user login in a mobile app
Server-to-server with rate limitsFine-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):

ConceptMeaning
Authorization codeOne-time code exchanged server-side โ€” secret never in browser
ID token (OIDC)Claims about user (sub, email, name)
Access tokenCall Google APIs on user's behalf
Your app's session/JWTWhat 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:

PatternUse
mTLSBoth client and server present TLS certificates
Internal signed tokenGateway mints service token after user authn
Workload identityK8s 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 forWeak 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

ScenarioModel
Instagram-style postsOwnership + admin role
Company admin dashboardRBAC
Shared document editorACL 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:

ControlProtects against
HTTPS / TLSToken interception on the wire
HttpOnly cookieJavaScript stealing session cookie (XSS)
SameSite=Lax/StrictCross-site request forgery on cookies
CSRF tokenForged state-changing requests with session cookie
CORSUntrusted origins calling your API from browsers
Short TTL + refreshStolen JWT window of abuse
MistakeBetter
JWT in localStorage for high-risk appsHttpOnly cookie or secure native keystore
Never rotate refresh tokensRotation on use; revoke family on theft
Log full JWT in application logsLog sub / request id only

Passwords and credentials (brief)

Even with OAuth, many apps still have email/password.

RuleWhy
Store hashes only (bcrypt, Argon2)DB leak doesn't expose plaintext passwords
Rate-limit /loginBrute-force protection
MFA for admin / paymentsStolen password isn't enough
Never send passwords in URLsLogs 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.

CallerAuthn pattern
Cron job exporting reportsAPI key or workload IAM role
Payment webhook from StripeVerify signature with shared secret
Mobile appUser JWT
Internal ledger servicemTLS + 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
QuestionExample 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

MistakeBetter
Trust user_id from JSON bodyDerive from validated token only
Auth only at gateway, never in serviceDefense in depth โ€” services enforce authz
401 vs 403 swapped401 = not identified; 403 = identified but denied
One global isAdmin flag in JWT for everythingRBAC + resource checks; minimal claims in token
OAuth access token passed to every microserviceIssue your internal identity token
No logout story with JWTShort TTL, refresh rotation, blocklist for high-risk
Public S3 + secret URLPrivate bucket + signed URL after authz (lesson 13)
Skip rate limits on /loginLockout, 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