Security for
System Design
Security isn't an afterthought โ it's an architectural concern from day one.
Security 01
Authentication vs Authorisation
These two concepts are frequently confused. Authentication answers "Who are you?" Authorisation answers "What are you allowed to do?" You must authenticate before you can be authorised.
Authentication (AuthN)
- Verifying identity
- "I am Alice โ here's my password/token"
- Mechanisms: passwords, MFA, OAuth, certificates
- Result: identity established (user ID, roles)
Authorisation (AuthZ)
- Verifying permissions
- "Alice is allowed to edit post 456"
- Models: RBAC, ABAC, ACL, policy-based
- Result: access granted or denied
RBAC vs ABAC
- RBAC (Role-Based Access Control): Users have roles (admin, editor, viewer). Roles have permissions. Simple, easy to audit. Most systems use this. Works for: org hierarchies, content platforms.
- ABAC (Attribute-Based Access Control): Access based on attributes of user, resource, and environment. e.g., "allow if user.department == resource.department AND time is business_hours." More flexible but complex. Works for: enterprise security, multi-tenant SaaS.
Security 02
OAuth 2.0
OAuth 2.0 is an authorisation framework that lets users grant third-party apps limited access to their resources without sharing their passwords. "Login with Google" is OAuth.
OAuth Flow (Authorization Code Grant)
User clicks "Login with Google" on YourApp.com
1. YourApp โ redirects user to Google:
accounts.google.com/oauth?
client_id=yourapp&
redirect_uri=yourapp.com/callback&
scope=email profile&
state=random123
2. User logs into Google, grants permission
3. Google โ redirects back to YourApp:
yourapp.com/callback?code=AUTH_CODE&state=random123
4. YourApp โ exchanges code for tokens (server-side):
POST https://oauth2.googleapis.com/token
{code: AUTH_CODE, client_secret: YOUR_SECRET}
โ {access_token, refresh_token, id_token}
5. YourApp uses access_token to call Google APIs
(fetch user profile, gmail, calendar, etc.)
Key point: the authorization code is short-lived and single-use. The actual token exchange happens server-side where your client_secret is safe. Never expose client_secret in browser JavaScript.
Security 03
JWT โ JSON Web Tokens
A JWT is a self-contained, signed token that carries claims about a user. The server can verify a JWT without a database lookup โ making it stateless and horizontally scalable.
JWT Structure: header.payload.signature
Header (base64): {"alg":"RS256","typ":"JWT"}
Payload (base64): {"sub":"user_123","role":"admin","exp":1735000000}
Signature: HMACSHA256(header + "." + payload, secret)
Verification:
1. Decode header + payload (anyone can do this โ not encrypted!)
2. Re-compute signature with server's secret
3. If signatures match โ token is authentic and unmodified
4. Check exp claim โ token not expired
5. Trust the claims
JWT pitfalls: (1) JWTs are base64-encoded, NOT encrypted. Anyone can read the payload. Never put sensitive data in a JWT. (2) JWTs can't be revoked before expiry without a blocklist (which requires a DB lookup, defeating statelessness). Use short expiry (15min) + refresh tokens. (3) Algorithm confusion attacks โ always specify the expected algorithm on verification.
Security 04
DDoS Protection
A Distributed Denial of Service attack floods your system with traffic from many sources, overwhelming it and denying service to legitimate users.
Defence in Depth
- Anycast CDN absorption: CDNs like Cloudflare have 100+ Tbps capacity globally. DDoS traffic is absorbed across edge nodes before reaching your origin. Most volumetric attacks are stopped here.
- Rate limiting at the edge: Block IPs sending >N requests/second. Cloudflare, AWS WAF support this.
- IP reputation lists: Block known botnet IPs, Tor exit nodes, suspicious ASNs.
- CAPTCHAs and challenges: Challenge suspicious traffic. Bots fail, humans pass.
- Connection rate limiting: Limit new TCP connections per IP per second at the network layer.
- Auto-scaling: Scale horizontally to absorb unexpected traffic. Not a complete defence but buys time.
- Scrubbing centres: For large attacks, ISPs route traffic through scrubbing centres that strip attack traffic before sending clean traffic to your servers.
Security 05
Zero Trust Architecture
"Never trust, always verify." Traditional security assumed everything inside the network perimeter was safe. Zero trust treats every request as potentially hostile โ regardless of whether it comes from inside or outside the network.
- Every request is authenticated: Even internal service-to-service calls require authentication (mTLS, service tokens).
- Least privilege access: Services only get permissions for exactly what they need. A billing service can't read user passwords.
- Assume breach: Design as if attackers are already inside. Lateral movement should be impossible due to micro-segmentation.
- Continuous verification: Don't trust a session indefinitely. Re-verify on sensitive operations. Short-lived tokens.
Security 06
Common Attacks & Defences
SQL Injection
โพAttacker injects SQL into user input: username = "admin'--" โ query becomes SELECT * FROM users WHERE name='admin'--' AND password='...' โ the password check is commented out. Fix: always use parameterised queries / prepared statements. Never concatenate user input into SQL.
XSS (Cross-Site Scripting)
โพAttacker injects malicious JavaScript into a page that other users see. Steals session cookies, redirects users, defaces pages. Fix: escape all user-generated content when rendering HTML. Use Content-Security-Policy headers. HttpOnly cookies (can't be read by JS).
CSRF (Cross-Site Request Forgery)
โพA malicious site tricks a logged-in user's browser into making a request to your API (cookies are automatically included). e.g., an image tag that triggers a bank transfer. Fix: CSRF tokens (random value in form, verified server-side), SameSite cookie attribute, check Origin/Referer headers.