Security
Security is a critical concern for every system. This guide covers authentication, authorization, encryption, and modern security architectures.
Authentication vs Authorization
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Security Flow β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββββββ βββββββββββββββββββββ β
β β Authentication βββββΆβ Authorization β β
β β "Who are you?" β β "What can you do?"β β
β ββββββββββββββββββββ βββββββββββββββββββββ β
β β β β
β βΌ βΌ β
β Username/Password Role-Based Access β
β OAuth/OIDC Permission Checks β
β Biometrics Policy Evaluation β
β MFA Resource Access β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββOAuth 2.0
Industry-standard protocol for authorization.
OAuth Roles
| Role | Description |
|---|---|
| Resource Owner | User who owns the data |
| Client | Application requesting access |
| Authorization Server | Issues tokens (Google, Auth0) |
| Resource Server | API holding protected resources |
Authorization Code Flow
ββββββββββββ βββββββββββββββββββββ
β User β β Authorization β
β (Browser)β β Server β
ββββββ¬ββββββ βββββββββββ¬ββββββββββ
β β
β 1. Click "Login with Google" β
βββββββββββββββββββββββββββββββββββββββββββββββΆβ
β β
β 2. Redirect to authorization URL β
ββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β 3. User authenticates & consents β
βββββββββββββββββββββββββββββββββββββββββββββββΆβ
β β
β 4. Redirect with authorization code β
ββββββββββββββββββββββββββββββββββββββββββββββββ
β β
β ββββββββββββββββ β
β β Client β β
β β (Backend) β β
β ββββββββ¬ββββββββ β
β β β
β β 5. Exchange code for tokens β
β ββββββββββββββββββββββββββββββΆβ
β β β
β β 6. Access + Refresh tokens β
β βββββββββββββββββββββββββββββββ
β β β
β β 7. Access protected API β
β ββββββββββββββββββββββββββββββΆβ Resource
β β β ServerOAuth Grant Types
| Grant Type | Use Case | Security |
|---|---|---|
| Authorization Code | Server-side apps | Most secure |
| Authorization Code + PKCE | Mobile/SPA apps | Secure for public clients |
| Client Credentials | Machine-to-machine | No user involved |
| Refresh Token | Get new access token | Long-lived sessions |
OAuth Best Practices
- Always use HTTPS
- Use PKCE for public clients (mobile, SPA)
- Short-lived access tokens (15 min - 1 hour)
- Rotate refresh tokens on use
- Validate redirect URIs strictly
- Use state parameter to prevent CSRF
OpenID Connect (OIDC)
Authentication layer on top of OAuth 2.0.
OAuth 2.0: Authorization (access to resources)
+
OpenID Connect: Authentication (user identity)
=
Complete auth solutionOIDC Additions
| Component | Purpose |
|---|---|
| ID Token | JWT containing user identity |
| UserInfo Endpoint | Get user profile |
| Standard Scopes | openid, profile, email |
| Standard Claims | sub, name, email, picture |
ID Token Structure
{
"iss": "https://auth.example.com",
"sub": "user123",
"aud": "client_app_id",
"exp": 1699999999,
"iat": 1699996399,
"name": "John Doe",
"email": "john@example.com"
}JWT (JSON Web Tokens)
Compact, URL-safe tokens for transmitting claims.
JWT Structure
Header.Payload.Signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
βββββββββββββββββββ
β Header β {"alg": "HS256", "typ": "JWT"}
βββββββββββββββββββ€
β Payload β {"sub": "123", "name": "John", "exp": 1699999999}
βββββββββββββββββββ€
β Signature β HMACSHA256(base64(header) + "." + base64(payload), secret)
βββββββββββββββββββJWT Validation
def validate_jwt(token, secret):
header, payload, signature = token.split('.')
# 1. Verify signature
expected_sig = hmac_sha256(f"{header}.{payload}", secret)
if signature != expected_sig:
raise InvalidSignature()
# 2. Decode payload
claims = base64_decode(payload)
# 3. Validate claims
if claims['exp'] < current_time():
raise TokenExpired()
if claims['iss'] != expected_issuer:
raise InvalidIssuer()
if claims['aud'] != our_client_id:
raise InvalidAudience()
return claimsJWT Best Practices
| Practice | Recommendation |
|---|---|
| Algorithm | RS256 (asymmetric) for distributed systems |
| Expiration | Short-lived (15 min for access tokens) |
| Storage | HttpOnly cookies (not localStorage) |
| Payload | Minimal claims, no sensitive data |
| Validation | Always verify signature, exp, iss, aud |
JWT vs Sessions
| Aspect | JWT | Sessions |
|---|---|---|
| Storage | Client-side | Server-side |
| Scalability | Stateless, scales easily | Requires session store |
| Revocation | Difficult (need blocklist) | Easy (delete session) |
| Size | Can grow large | Just session ID |
| Use Case | APIs, microservices | Traditional web apps |
Zero Trust Architecture
βNever trust, always verifyβ - every request must be authenticated and authorized.
Traditional vs Zero Trust
Traditional (Perimeter-based):
βββββββββββββββββββββββββββββββββββββββββββ
β Corporate Network β
β βββββββββββ βββββββββββ βββββββββββ β
β β Service ββββ Service ββββ Service β β β Trust inside
β βββββββββββ βββββββββββ βββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββ
β
Firewall β Trust boundary
β
Internet (untrusted)
Zero Trust:
βββββββββββββββββββββββββββββββββββββββββββ
β βββββββββββ βββββββββββ βββββββββββ β
β β Service ββ?ββ Service ββ?ββ Service β β β Verify everything
β β + Auth β β + Auth β β + Auth β β
β βββββββββββ βββββββββββ βββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββ
Every request authenticated & authorizedZero Trust Principles
| Principle | Implementation |
|---|---|
| Verify explicitly | Authenticate every request |
| Least privilege | Minimal permissions needed |
| Assume breach | Limit blast radius |
| Micro-segmentation | Network isolation per service |
| Continuous validation | Re-verify throughout session |
Zero Trust Components
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Zero Trust Architecture β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β Identity β β Device β β Network β β
β β Provider β β Trust β β Micro-seg β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β β β β
β ββββββββββββββββββββΌβββββββββββββββββββ β
β β β
β ββββββββΌβββββββ β
β β Policy β β
β β Engine β β
β ββββββββ¬βββββββ β
β β β
β ββββββββΌβββββββ β
β β Access β β
β β Decision β β
β βββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEncryption
Encryption at Rest
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Data at Rest β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Application Data β
β β β
β βΌ β
β βββββββββββββββ β
β β DEK β Data Encryption Key β
β β (per-data) β Encrypts actual data β
β ββββββββ¬βββββββ β
β β β
β ββββββββΌβββββββ β
β β KEK β Key Encryption Key β
β β (per-user) β Encrypts DEK β
β ββββββββ¬βββββββ β
β β β
β ββββββββΌβββββββ β
β β Master Key β Stored in HSM/KMS β
β β (KMS) β (AWS KMS, HashiCorp Vault) β
β βββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββEncryption in Transit
| Protocol | Use Case |
|---|---|
| TLS 1.3 | HTTPS, API calls |
| mTLS | Service-to-service |
| SSH | Server access |
| VPN/WireGuard | Network tunneling |
Symmetric vs Asymmetric
| Type | Algorithms | Use Case |
|---|---|---|
| Symmetric | AES-256-GCM | Bulk data encryption |
| Asymmetric | RSA, ECDSA | Key exchange, signatures |
| Hybrid | Both | TLS (asymmetric for key exchange, symmetric for data) |
API Security
API Authentication Methods
| Method | Security | Use Case |
|---|---|---|
| API Key | Low | Simple integrations |
| OAuth 2.0 | High | User-authorized access |
| mTLS | Very High | Service-to-service |
| HMAC Signatures | High | Webhook verification |
Rate Limiting
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Rate Limiting β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Token Bucket: β
β βββββββββββββββββββββββββββββββββββββββ β
β β Bucket: [ββββββββββ] β β
β β β² β β
β β Tokens added at fixed rate β β
β β Request consumes 1 token β β
β β Empty bucket = rate limited β β
β βββββββββββββββββββββββββββββββββββββββ β
β β
β Limits by: β
β - IP address β
β - User ID β
β - API key β
β - Endpoint β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββInput Validation
# Always validate and sanitize
def create_user(request):
# 1. Schema validation
validate_schema(request.body, UserSchema)
# 2. Type checking
email = str(request.body.get('email', ''))
# 3. Format validation
if not is_valid_email(email):
raise ValidationError("Invalid email")
# 4. Business rules
if User.exists(email):
raise ValidationError("Email already registered")
# 5. Sanitize before storage
name = sanitize_html(request.body.get('name'))OWASP Top 10
Critical Vulnerabilities
| Rank | Vulnerability | Prevention |
|---|---|---|
| 1 | Broken Access Control | Enforce authorization on every request |
| 2 | Cryptographic Failures | Use strong encryption, proper key management |
| 3 | Injection | Parameterized queries, input validation |
| 4 | Insecure Design | Threat modeling, secure patterns |
| 5 | Security Misconfiguration | Hardened defaults, security headers |
| 6 | Vulnerable Components | Regular updates, dependency scanning |
| 7 | Auth Failures | MFA, strong passwords, secure sessions |
| 8 | Data Integrity Failures | Verify signatures, validate updates |
| 9 | Logging Failures | Comprehensive logging, monitoring |
| 10 | SSRF | Validate URLs, allowlist destinations |
SQL Injection Prevention
// β Vulnerable
String query = "SELECT * FROM users WHERE id = " + userId;
// β
Safe - Parameterized query
PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM users WHERE id = ?"
);
stmt.setString(1, userId);XSS Prevention
// β Vulnerable
element.innerHTML = userInput;
// β
Safe - Text content
element.textContent = userInput;
// β
Safe - Sanitize if HTML needed
element.innerHTML = DOMPurify.sanitize(userInput);Security Headers
# Prevent XSS
Content-Security-Policy: default-src 'self'; script-src 'self'
# Prevent clickjacking
X-Frame-Options: DENY
# Force HTTPS
Strict-Transport-Security: max-age=31536000; includeSubDomains
# Prevent MIME sniffing
X-Content-Type-Options: nosniff
# Control referrer
Referrer-Policy: strict-origin-when-cross-originInterview Quick Reference
Common Questions
-
βHow would you secure a REST API?β
- OAuth 2.0 / JWT authentication
- HTTPS everywhere
- Rate limiting
- Input validation
- Security headers
- Logging and monitoring
-
βExplain OAuth 2.0 Authorization Code flowβ
- User clicks login
- Redirect to auth server
- User authenticates
- Auth code returned
- Backend exchanges code for tokens
- Access protected resources
-
βJWT vs Sessions - when to use which?β
- JWT: APIs, microservices, stateless needs
- Sessions: Traditional web apps, easy revocation needed
Security Checklist
- Authentication implemented? (OAuth, OIDC)
- Authorization on every endpoint?
- Input validation and sanitization?
- Encryption at rest and in transit?
- Secure headers configured?
- Rate limiting in place?
- Logging and monitoring?
- Dependencies regularly updated?
- Secrets management? (not in code)
- Security testing? (SAST, DAST, pen testing)
Last updated on