Guide / System design Fundamentals
Authentication, authorization and API security
Sessions vs tokens, OAuth 2.0 and OIDC flows, JWT pitfalls, RBAC vs ABAC, secrets and encryption, and the OWASP risks every API designer should be able to name and fix.
Security questions in design interviews are usually: “how do users log in, how do services trust each other, and how do you stop abuse”. Answer by naming the mechanism, the failure mode and the mitigation.
Fundamentals#
S.1 Authentication vs authorization#
Authentication (AuthN) = who are you. Authorization (AuthZ) = what may you do. Always enforce authorization on the server, per object, on every request.
S.2 Sessions vs tokens#
| Server-side session | Token (JWT access token) | |
|---|---|---|
| State | Server stores session (Redis); client holds an opaque ID in a cookie | Self-contained signed claims; server verifies signature, no lookup |
| Revocation | Immediate (delete the session) | Hard before expiry: short TTL plus a denylist or token versioning |
| Scale | Needs shared store | Stateless verification across services |
| Best for | Browser apps (HttpOnly, Secure, SameSite cookies) | APIs, mobile, service-to-service |
Common design: short-lived access token (5–15 min) + longer refresh token (days, rotated on use, stored securely, revocable server-side). Refresh token rotation with reuse detection (a reused old refresh token means theft: revoke the whole family).
S.3 OAuth 2.0 and OIDC#
OAuth 2.0 is delegated authorization (an app acts on a user’s behalf with scopes); OpenID Connect (OIDC) adds authentication (an ID token saying who the user is).
| Flow | Use for |
|---|---|
| Authorization Code + PKCE | Web, SPA and mobile apps with a user: redirect to the identity provider, get a code, exchange it (with the PKCE verifier) for tokens. The default. |
| Client credentials | Service-to-service, no user |
| Device code | TVs and CLIs |
| Implicit, password grant | Deprecated, do not use |
Roles: resource owner (user), client (app), authorization server (Okta, Auth0, Cognito, Keycloak), resource server (your API). Validate access tokens by checking signature (JWKS), iss, aud, exp, and scopes.
S.4 JWT: strengths and pitfalls#
Structure: header.payload.signature (signed, not encrypted: do not put secrets in it). Pitfalls: accepting alg: none or letting the token pick the algorithm, not checking aud/iss, long expiry with no revocation, storing tokens in localStorage (XSS theft; prefer HttpOnly cookies for browsers), huge tokens, and using symmetric secrets shared across many services (prefer asymmetric RS256/ES256 with a public JWKS endpoint). Rotate signing keys with kid.
S.5 Authorization models#
| Model | Idea | Fit |
|---|---|---|
| RBAC | Users have roles; roles have permissions | Most business apps; simple, can explode in roles |
| ABAC | Decisions from attributes (user, resource, environment) via policies | Fine-grained, contextual rules (“managers can approve under 10K in their region”) |
| ReBAC | Permission from relationships in a graph (Google Zanzibar, SpiceDB, OpenFGA) | Sharing models like documents, folders, teams |
| ACLs | Per-object lists | Simple object sharing |
Centralise policy (OPA, Cedar, a permissions service) with caching; enforce at the gateway coarsely and in the service precisely. Multi-tenant: tenant_id in every query and token, plus tests that cross-tenant access fails.
S.6 Service-to-service security#
mTLS (SPIFFE/SPIRE identities, mesh-managed certificates), short-lived signed service tokens, least-privilege network policies (zero trust: never trust the network position), and no shared long-lived credentials.
S.7 Secrets, encryption and data protection#
- Secrets: a secrets manager (Vault, AWS Secrets Manager), injected at runtime, rotated, never in git, images or logs; short-lived credentials (IAM roles, workload identity).
- In transit: TLS 1.2+ everywhere. At rest: disk/DB encryption, envelope encryption (data keys encrypted by a KMS master key) so rotation and access control are manageable. Field-level encryption for PII and card data; tokenisation to keep card numbers out of your systems (reduces PCI scope).
- Passwords: hash with Argon2id, bcrypt or scrypt (salted, slow). Never reversible encryption or fast hashes. Add MFA (TOTP, WebAuthn passkeys), breach-password checks and rate limits (Rate limiting).
- PII hygiene: data minimisation, retention limits, masking in logs, access auditing, deletion pipelines (GDPR/DPDP).
S.8 OWASP-style checklist for APIs#
| Risk | Mitigation |
|---|---|
| Broken object-level authorization (IDOR) | Check ownership on every object access; query by id AND tenant_id |
| Broken authentication | MFA, rate-limited login, secure session handling, short token lifetime |
| Excessive data exposure / mass assignment | DTOs with explicit allowlists, never bind request bodies to models |
| Injection (SQL, NoSQL, command, prompt) | Parameterised queries, input validation, least-privilege DB users |
| XSS / CSRF | Output encoding, CSP, HttpOnly + SameSite cookies, CSRF tokens for cookie auth |
| SSRF | Allowlist outbound hosts, block internal IPs and metadata endpoints |
| Security misconfiguration | Hardened defaults, no debug in prod, CORS allowlist, security headers (HSTS, CSP) |
| Vulnerable dependencies | SCA scans, pinned versions, SBOM, patching SLAs |
| Insufficient logging | Audit logs of auth events and sensitive actions, tamper-resistant, alerts |
| Unrestricted resource consumption | Rate limits, size limits, timeouts, pagination caps |
Most asked questions#
1. Session vs JWT: which and why? Cookies with server sessions for browser apps (easy revocation, safer storage); short-lived JWTs plus refresh tokens for APIs and mobile and microservices; state the revocation trade-off.
2. Explain OAuth 2.0 authorization code flow with PKCE. App redirects to the IdP with a code challenge, user logs in and consents, IdP redirects back with a code, the app exchanges the code plus verifier for tokens; PKCE prevents code interception.
3. OAuth vs OIDC vs SAML? OAuth: authorization delegation; OIDC: authentication on top of OAuth (ID token); SAML: older XML-based enterprise SSO.
4. How do you store passwords? Salted, slow hash (Argon2id/bcrypt), peppered optionally, plus MFA and breach checks.
5. How do you secure service-to-service calls? mTLS or signed tokens with short TTL, least-privilege policies, network segmentation.
6. How do you prevent IDOR? Server-side ownership checks on every request and tenant-scoped queries.
7. How do you design RBAC for a multi-tenant SaaS? Tenant-scoped roles, permission checks via a central policy service, tenant ID in tokens and queries, audit logs, and tests for cross-tenant leaks.
Senior-level questions#
1. “A JWT was stolen. How do you respond?” Short expiry limits damage; revoke by rotating the signing key (heavy), token version/session ID check with a denylist for high-value actions, revoke refresh tokens, force re-auth, investigate and add device binding.
2. “How do you implement logout everywhere with stateless tokens?” Maintain a per-user token_version or session list in a fast store; the gateway checks it (small cache TTL); or use opaque tokens with introspection for sensitive apps.
3. “How do you protect against credential stuffing?” Per-account and per-IP rate limits, breach-password screening, bot detection, MFA, anomaly detection and progressive delays, passkeys.
4. “Design authorization for Google-Docs-style sharing.” ReBAC: tuples (user, relation, object) and inheritance via folders; a Zanzibar-like service with caching and consistency tokens (“zookies”) so a revoked permission is not served stale.
5. “Where do secrets leak in practice?” Logs, error messages, CI output, container images, client bundles, git history; prevent with scanning, short-lived credentials and secret managers.
6. “How do you do zero-trust for internal services?” Authenticate and authorise every call, mTLS, workload identity, least privilege, no implicit trust of the network, and audit.
Quiz#
1. Which claims must a resource server validate in a JWT?
Signature, iss, aud, exp/nbf, and the scopes or roles needed.
2. Why PKCE for mobile and SPA?
They cannot keep a client secret; PKCE binds the authorization code to the client that started the flow so intercepted codes are useless.
3. What is refresh token rotation?
Each use issues a new refresh token and invalidates the old; reuse of an old one signals theft and revokes the family.
4. 401 or 403 for a valid token lacking scope?
403 (authenticated but not permitted).
5. What is envelope encryption?
Data is encrypted with a data key, and that key is encrypted by a master key in a KMS, simplifying rotation and access control.