Security in System Design
Authentication, authorization, OAuth/OIDC, JWTs, TLS, encryption, secrets and common attacks.
What is it?
Security in system design is about deciding, at the architecture level, who can do what, how data is protected, and where attackers can get in.
Key building blocks:
- Authentication (authN): proving who someone is (password, passkey, SSO). - Authorization (authZ): deciding what that identity may do (roles, permissions, ownership checks). - OAuth 2.0: a framework for granting an app limited access to resources without sharing a password. OpenID Connect (OIDC) adds a standard identity layer on top for login. - Tokens like JWTs carry signed claims so services can verify a caller without a database lookup. - TLS encrypts data in transit; mTLS also authenticates the client. Encryption at rest protects stored data. - Secrets management keeps keys and passwords out of code. - Least privilege: every user, service and key gets only the access it needs.
Explain like I'm 10
Authentication is showing your ID at a hotel's front desk. Authorization is your key card opening your room and the gym, but not other rooms. An OAuth access token is a valet key: it lets someone drive your car but not open the trunk, and it can be revoked without changing your house keys.
Examples
Verifying a JWT and checking authorization
import { jwtVerify, createRemoteJWKSet } from "jose";
const issuerKeys = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
async function handleDeleteInvoice(request) {
const token = request.headers.authorization?.replace("Bearer ", "");
if (!token) return { status: 401 };
// authN: signature, expiry, issuer and audience are all checked.
const { payload } = await jwtVerify(token, issuerKeys, {
issuer: "https://auth.example.com",
audience: "billing-api",
algorithms: ["RS256"], // never accept "none" or unexpected algorithms
});
// authZ: the token says who you are; we still check what you may do.
const invoice = await db.findInvoice(request.params.id);
if (!invoice) return { status: 404 };
if (invoice.accountId !== payload.account_id) return { status: 403 };
await db.deleteInvoice(invoice.id);
return { status: 204 };
}Verifying the token proves identity. Checking that this invoice belongs to the caller's account is authorization; skipping it is the classic broken-object-level-authorization bug.
OAuth 2.0 Authorization Code flow with PKCE (simplified)
1. App creates random code_verifier, sends SHA-256 hash as code_challenge
GET https://auth.example.com/authorize?response_type=code
&client_id=app123&redirect_uri=https://app.example.com/callback
&scope=openid%20profile&state=xyz&code_challenge=...&code_challenge_method=S256
2. User logs in and consents at the authorization server
3. Browser redirected to https://app.example.com/callback?code=AUTH_CODE&state=xyz
4. App checks state, then exchanges the code (back channel):
POST /token grant_type=authorization_code&code=AUTH_CODE&code_verifier=...
5. Response: access_token (+ refresh_token, + id_token with OIDC)The short-lived code is useless without the code_verifier only the app knows, so an intercepted code can't be redeemed. The state parameter protects against CSRF on the callback.
How it works
OAuth 2.0 flows (grants)
- Authorization Code + PKCE: for web apps, SPAs and mobile apps acting on behalf of a user. The recommended default. The older Implicit flow is deprecated. - Client Credentials: service-to-service, no user involved. - Device Authorization: TVs and CLIs without a convenient browser. - Refresh tokens: exchange for new short-lived access tokens without re-login.
OIDC adds an ID token (a JWT describing the authenticated user), a userinfo endpoint and standard discovery. OAuth alone is about access, not login.
JWT trade-offs: a JWT is signed (not encrypted by default), so anyone can read its claims. Services verify it locally, which scales well. But it can't be revoked before it expires without extra machinery (a denylist or checking a session store), so keep access tokens short-lived (minutes) and use refresh tokens. Pin the expected algorithm and validate exp, iss and aud. Server-side sessions with an opaque ID are easier to revoke and are often the better choice for a single web app.
TLS and mTLS: TLS encrypts traffic and authenticates the server by certificate. mTLS makes both sides present certificates, which is common for service-to-service traffic in zero-trust networks and service meshes.
Encryption at rest: disk or database encryption protects against stolen media or snapshots. Envelope encryption is standard: data is encrypted with a data key, and the data key is encrypted with a master key held in a KMS or HSM, so rotating or revoking the master key doesn't require re-encrypting everything.
Secrets management: store secrets in a vault or cloud secrets manager, inject at runtime, rotate regularly, prefer short-lived dynamic credentials, and never commit them to git or bake them into images.
Least privilege and defense in depth: scoped IAM roles per service, network segmentation, separate credentials per environment, and audit logs.
Common attack surfaces
- Injection (SQL, command, template): untrusted input interpreted as code. Use parameterized queries and avoid shelling out with user input. - SSRF: the server is tricked into fetching an attacker-chosen URL, such as internal services or the cloud metadata endpoint (169.254.169.254) to steal credentials. Allowlist destinations, block private address ranges (after DNS resolution), and use IMDSv2 on AWS. - DDoS: floods of traffic. Absorb at the edge (CDN, anycast, cloud DDoS protection), rate-limit, and autoscale with caps. - Broken authorization: the most common API flaw; check ownership on every object access.
Request path with security controls
Client --TLS--> CDN / WAF / DDoS protection --> API gateway (authN: verify token, rate limit)
|
v
Service A --mTLS--> Service B (authZ in each service)
| |
Secrets manager Database (encrypted at rest,
(short-lived creds) least-privilege DB user)
Envelope encryption
plaintext --(data key)--> ciphertext data key --(KMS master key)--> encrypted data key
store: ciphertext + encrypted data key master key never leaves the KMSWhy does it exist?
Every networked system is attacked constantly and automatically. Security retrofitted after launch is expensive and leaky; decisions like where tokens are verified, how services authenticate each other and where secrets live are architectural, and hard to change later.
When to use it
Always. Specifically: OIDC for user login via an identity provider; OAuth Authorization Code + PKCE for apps acting for users; Client Credentials or mTLS for service-to-service; TLS everywhere, including internal traffic; envelope encryption for sensitive data at rest; a secrets manager from the first deploy.
When not to use it
Don't build your own crypto, password hashing or token format; use vetted libraries and standard protocols. Don't use JWTs as long-lived sessions you need to revoke instantly; server-side sessions fit better. Don't use OAuth just to log users into your own single app if a simple, secure session login does the job.
Common mistakes
Confusing authentication with authorization: verifying the token but never checking that the user owns the resource.
Storing sensitive data in JWT claims, forgetting that JWTs are readable by anyone (signed, not encrypted).
Accepting whatever algorithm the JWT header claims, including 'none', instead of pinning the expected one.
Committing secrets to git or baking them into container images.
Fetching user-supplied URLs server-side without SSRF protections, exposing internal services and cloud metadata.
Practice exercises
- Easy:
For each, say whether it's authN or authZ: logging in with a passkey, checking an admin role, verifying a JWT signature, ensuring a user can only view their own orders.
- Medium:
Design token handling for a SPA and its API: which OAuth flow, where tokens are stored, token lifetimes, and how logout and revocation work.
- Hard:
Threat-model a 'fetch a preview image from this URL' feature. List the SSRF vectors (including redirects and DNS rebinding) and design the defenses.
Interview questions
What's the difference between authentication and authorization?
Authentication verifies who the caller is. Authorization decides what that authenticated caller is allowed to do. A request can be authenticated (no 401) and still forbidden (403).
What's the difference between OAuth 2.0 and OpenID Connect?
OAuth 2.0 is for delegated authorization: getting an access token to call an API. OIDC is an identity layer on top that adds an ID token and standard claims so the app learns who the user is, i.e. login.
Which OAuth flow should a SPA or mobile app use, and why PKCE?
Authorization Code with PKCE. Public clients can't keep a client secret, so PKCE binds the authorization code to a random verifier only the app holds; an intercepted code can't be exchanged without it. The Implicit flow is deprecated.
What are the pros and cons of JWTs?
Pros: self-contained, verifiable locally without a database call, good for distributed services. Cons: hard to revoke before expiry, claims are readable, tokens can grow large, and misconfigured validation (algorithm, audience) is a common vulnerability. Keep them short-lived.
How do you revoke a JWT?
You can't make an issued JWT invalid by itself. Options: short expiry plus refresh tokens that you can revoke server-side, a denylist of token ids (jti) checked on each request, or rotating signing keys for mass revocation.
What is mTLS and when is it used?
Mutual TLS: both client and server present and verify certificates, so each side authenticates the other and traffic is encrypted. It's common for service-to-service communication, often automated by a service mesh.
What is envelope encryption?
Encrypting data with a data encryption key, then encrypting that key with a master key held in a KMS or HSM. The master key never leaves the KMS, and rotating it only requires re-encrypting the small data keys.
What is SSRF and how do you prevent it?
Server-Side Request Forgery: tricking a server into making requests to attacker-chosen destinations, such as internal admin APIs or cloud metadata endpoints. Prevent it with destination allowlists, blocking private and link-local IPs after DNS resolution (re-checking on redirects), network egress controls, and IMDSv2.
How do you design for DDoS resilience?
Absorb volumetric attacks at the edge with a CDN or cloud DDoS service and anycast, filter with a WAF, rate-limit per client and per endpoint, cache aggressively, and protect expensive endpoints. Autoscale, but with limits, so an attack doesn't become a huge bill.
What does least privilege look like for a microservice?
Its own identity and credentials, an IAM role allowing only the specific actions and resources it needs, a database user restricted to its own tables, network policies allowing only required callers, and short-lived credentials from a secrets manager.