← Back to Index

10. Security

Authentication

Authentication verifies who a user is. Common approaches:

# OAuth 2.0 Authorization Code Flow
User clicks "Login with Google" → redirected to Google
Google asks for consent → Google redirects to app with code
Backend exchanges code + client_secret for access_token
Backend uses access_token to fetch user profile from Google API

Authorization

Authorization determines what a user can do after authentication.

ModelDescriptionExample
RBACRole-Based Access ControlAdmin, Editor, Viewer roles
ABACAttribute-Based Access Control"Can edit documents created in the last 30 days"
PBAC/PBACPolicy-Based Access ControlIAM policies (AWS)
ACLAccess Control ListsPer-object permissions (file systems)
# RBAC Policy (Pseudocode)
roles:
  admin: [read, write, delete, manage_users]
  editor: [read, write]
  viewer: [read]

def authorize(user, action, resource):
  user_roles = get_roles(user)
  return any(action in role.permissions for role in user_roles)

Data Protection

Encryption

Data Masking

Replace sensitive data (PII, credit card numbers) with masked versions in logs, dev databases, and UI: ****-****-****-1234.

Key Management

Use a Key Management Service (AWS KMS, Azure Key Vault, HashiCorp Vault) to store, rotate, and audit encryption keys. Never hardcode keys in source code.

Infrastructure Security

Common Threats & Mitigations

ThreatDescriptionMitigation
SQL InjectionMalicious SQL inserted into queriesParameterized queries, ORM, input validation
XSSMalicious scripts injected into web pagesContent-Security-Policy, output escaping, sanitization
CSRFCross-site request forgeryCSRF tokens, SameSite cookies
Man-in-the-MiddleIntercepting communicationHTTPS, certificate pinning, HSTS
DDoSOverwhelming system with trafficCDN, rate limiting, auto-scaling, scrubbing services
Exercise: Design an authentication and authorization system for a healthcare API. Requirements: patients can view their own records, doctors can view/edit assigned patients, admins can manage users. All access must be logged. Data must be encrypted at rest and in transit. Describe your auth model, encryption strategy, and audit approach.