Security
Security Patterns
Security is not a feature β it's a requirement. Authentication, authorization, encryption, and secure communication must be designed into the system from the start.
- Authentication β Verify identity
- Authorization β Enforce access control
- Encryption β Protect data in transit and at rest
Security is only as strong as its weakest link.
Authentication
Verifying that a user is who they claim to be.
DfAuthentication
Authentication is the process of verifying the identity of a user, device, or system. It answers the question "Who are you?" Common mechanisms include passwords, multi-factor authentication (MFA), biometrics, and token-based authentication.
Authentication Factors
| Factor Type | Examples |
|---|---|
| Knowledge | Password, PIN, security questions |
| Possession | Phone (SMS/authenticator app), hardware token |
| Inherence | Fingerprint, face recognition, retina scan |
Multi-factor authentication (MFA) combines two or more factor types. Password + authenticator app (knowledge + possession) is significantly more secure than password alone. NIST recommends MFA for all sensitive systems.
JSON Web Tokens (JWT)
DfJWT
A JSON Web Token (JWT) is a compact, URL-safe means of representing claims between two parties. A JWT consists of three parts: header (algorithm and token type), payload (claims), and signature (verification). JWTs are stateless β the server doesn't store session data; all information is in the token.
JWT Structure
Header.Payload.Signature
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTIzIiwicm9sZSI6ImFkbWluIn0.abc123signature
| Part | Contents |
|---|---|
| Header | Algorithm (HS256, RS256), token type |
| Payload | User ID, roles, expiration, custom claims |
| Signature | HMAC or RSA signature for verification |
Never store sensitive data in JWT payloads. The payload is base64-encoded, not encrypted. Anyone with the token can read the claims. Store only non-sensitive identifiers and roles.
JWT vs Session Tokens
| Aspect | JWT | Session Token |
|---|---|---|
| Storage | Client (localStorage/cookie) | Server (Redis/DB) |
| State | Stateless | Stateful |
| Scalability | Excellent (no server state) | Requires shared store |
| Revocation | Difficult (until expiry) | Easy (delete session) |
| Size | Larger (contains claims) | Smaller (opaque ID) |
OAuth 2.0
Delegated authorization framework for third-party access.
DfOAuth 2.0
OAuth 2.0 is an authorization framework that allows third-party applications to obtain limited access to a user's resources without exposing credentials. The user grants access to their data on one service (resource server) to another service (client), mediated by an authorization server.
Authorization
Controlling what authenticated users can access.
DfAuthorization
Authorization determines what an authenticated user is allowed to do. It answers "What can you access?" Common models include Role-Based Access Control (RBAC), Attribute-Based Access Control (ABAC), and Access Control Lists (ACLs).
RBAC vs ABAC
| Model | Description | Example |
|---|---|---|
| RBAC | Permissions assigned to roles | Admin can delete, User can read |
| ABAC | Permissions based on attributes | Allow if user.department == resource.owner |
Authorization Decision
Here,
- =Authenticated user with attributes
- =Requested action (read, write, delete)
- =Target resource with attributes
Encryption
Protecting data in transit and at rest.
DfEncryption
Encryption transforms plaintext into ciphertext using an algorithm and key. At rest encryption protects stored data (disk encryption, database encryption). In transit encryption protects data during transmission (TLS/HTTPS). End-to-end encryption ensures only communicating parties can read data.
TLS (Transport Layer Security)
DfTLS
TLS (formerly SSL) provides encrypted communication between clients and servers. TLS 1.3 is the current standard, offering improved security and performance over TLS 1.2. TLS provides confidentiality, integrity, and authentication for data in transit.
Always use TLS 1.2+ for all HTTP communication. Disable older protocols (SSL 3.0, TLS 1.0, TLS 1.1). Use strong cipher suites and enable HSTS (HTTP Strict Transport Security).
Security Best Practices
| Practice | Description |
|---|---|
| Principle of least privilege | Grant minimum necessary permissions |
| Defense in depth | Multiple security layers |
| Input validation | Validate and sanitize all inputs |
| Output encoding | Encode output to prevent injection |
| Rate limiting | Prevent brute force and abuse |
| Audit logging | Log all security-relevant events |
| Secret management | Never commit secrets; use vaults |
Use a secrets manager (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault) for all sensitive credentials. Rotate secrets regularly. Never hardcode passwords, API keys, or certificates in source code.
Practice Exercises
-
Design: Design an authentication system for a SaaS application supporting OAuth 2.0, SAML, and email/password. Include token refresh, session management, and MFA.
-
JWT: Implement JWT-based authentication with access tokens (15-minute expiry) and refresh tokens (7-day expiry). How do you handle token revocation?
-
Authorization: Design an RBAC system for a hospital management system with roles: doctor, nurse, admin, patient. Each role has different access to patient records.
-
Encryption: Design encryption at rest for a database storing medical records. Include key management, rotation, and compliance requirements (HIPAA).
Key Takeaways:
- Authentication verifies identity; authorization controls access
- JWTs are stateless tokens for authentication; OAuth 2.0 enables delegated authorization
- RBAC assigns permissions to roles; ABAC uses attributes for fine-grained control
- Use TLS 1.2+ for all communication; encrypt sensitive data at rest
- Follow defense in depth: multiple security layers
- Never hardcode secrets; use secret management systems
- Log all security events for audit and incident response
What to Learn Next
-> Service Mesh Envoy, Istio, and automatic mTLS.
-> Proxy and Reverse Proxy Forward proxy, Nginx, and SSL termination.
-> Rate Limiting Token bucket, sliding window, and distributed rate limiting.
-> CDN Edge caching and security at the edge.
-> Observability Logging, metrics, tracing, and monitoring.
-> API Design REST, GraphQL, gRPC, and API security.