Security and Auth at Scale
Security is a design property, not a feature added at the end. At scale, the questions become architectural: where is a user authenticated, how do dozens of services know who is calling, how are passwords and secrets stored, and how is the blast radius of a breach kept small?
| Concept | Question it answers | Typical mechanism |
|---|---|---|
| Authentication (authn) | Who are you? | Passwords + MFA, passkeys (WebAuthn), SSO via OpenID Connect |
| Authorization (authz) | What may you do? | Roles (RBAC), attributes/policies (ABAC), relationship-based (ReBAC) |
| Session / token | How do later requests prove it? | Session cookie, JWT access token + refresh token |
| Service identity | Which service is calling? | mTLS certificates, workload identity (SPIFFE), signed tokens |
| Secrets | Where do keys and passwords live? | A secrets manager (Vault, AWS Secrets Manager, KMS), never in code |
Storing passwords
Never store passwords, not even encrypted. Store a slow, salted hash. A unique random salt per user makes identical passwords produce different hashes and defeats precomputed tables; a slow function (bcrypt, scrypt, Argon2, PBKDF2 with many iterations) makes brute-forcing stolen hashes expensive.
import hashlib
import hmac
def pbkdf2_sha256(password, salt, iterations):
# PBKDF2 written out (one 32-byte block): HMAC applied over and over.
# Real code: hashlib.pbkdf2_hmac("sha256", ...) or an Argon2 library.
u = hmac.new(password, salt + b"\x00\x00\x00\x01", hashlib.sha256).digest()
result = int.from_bytes(u, "big")
for _ in range(iterations - 1):
u = hmac.new(password, u, hashlib.sha256).digest()
result ^= int.from_bytes(u, "big")
return result.to_bytes(32, "big")
def hash_password(password, salt, iterations=20_000):
return pbkdf2_sha256(password.encode(), salt, iterations).hex()
# Fixed salts here so the output is reproducible; in real code use os.urandom(16)
users = {
"ana": (b"salt-ana-123456", hash_password("correct horse", b"salt-ana-123456")),
"ben": (b"salt-ben-654321", hash_password("correct horse", b"salt-ben-654321")),
}
print("same password, different hashes:", users["ana"][1][:16], users["ben"][1][:16])
def login(user, attempt):
salt, stored = users[user]
return hmac.compare_digest(stored, hash_password(attempt, salt)) # constant-time compare
print("ana / correct horse:", login("ana", "correct horse"))
print("ana / Correct horse:", login("ana", "Correct horse"))same password, different hashes: 64f5a47e09ffa880 a1a6ee5592cb1f44
ana / correct horse: True
ana / Correct horse: False
The work factor turns into an attacker's bill. Rough numbers for an attacker with GPUs:
guesses_per_second = {"plain SHA-256": 10_000_000_000, "PBKDF2 100k iterations": 100_000, "Argon2id (64 MB)": 1_000}
keyspace = 26 ** 8 # 8 lowercase letters
for scheme, rate in guesses_per_second.items():
seconds = keyspace / rate
if seconds < 3600:
human = f"{seconds:.0f} seconds"
elif seconds < 86_400 * 365:
human = f"{seconds / 86_400:.1f} days"
else:
human = f"{seconds / (86_400 * 365):.0f} years"
print(f"{scheme:<24} try all 8-letter lowercase passwords in {human}")plain SHA-256 try all 8-letter lowercase passwords in 21 seconds
PBKDF2 100k iterations try all 8-letter lowercase passwords in 24.2 days
Argon2id (64 MB) try all 8-letter lowercase passwords in 7 years
Sessions vs tokens
| Server-side session | Signed token (JWT) | |
|---|---|---|
| What the client holds | A random session id in a cookie | A self-contained, signed token with claims |
| Validation | Look up the id in a session store (Redis) | Verify the signature locally; no lookup |
| Revocation | Delete the session: instant | Hard until expiry: keep access tokens short (5-15 min) and revoke refresh tokens |
| Fits | Monoliths, web apps | Many services and APIs: each can verify without calling the auth service |
A JWT is base64url(header).base64url(claims).signature. Here's the verification logic with an HMAC-signed token, the same check each microservice would run:
import base64
import hashlib
import hmac
import json
KEY = b"shared-signing-key"
def b64(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def sign(claims):
header = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
body = b64(json.dumps(claims, sort_keys=True).encode())
sig = b64(hmac.new(KEY, f"{header}.{body}".encode(), hashlib.sha256).digest())
return f"{header}.{body}.{sig}"
def verify(token, now):
header, body, sig = token.split(".")
expected = b64(hmac.new(KEY, f"{header}.{body}".encode(), hashlib.sha256).digest())
if not hmac.compare_digest(sig, expected):
return "rejected: bad signature"
claims = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
if now >= claims["exp"]:
return "rejected: expired"
return f"ok: user {claims['sub']} with roles {claims['roles']}"
token = sign({"sub": "user-42", "roles": ["customer"], "exp": 1_000_900})
print("token:", token[:40] + "...")
print(verify(token, now=1_000_000))
print(verify(token, now=1_001_000))
header, body, sig = token.split(".")
forged_body = b64(json.dumps({"sub": "user-42", "roles": ["admin"], "exp": 1_000_900}, sort_keys=True).encode())
print(verify(f"{header}.{forged_body}.{sig}", now=1_000_000))token: eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9...
ok: user user-42 with roles ['customer']
rejected: expired
rejected: bad signature
In production, prefer asymmetric signatures (RS256/ES256): the auth service signs with a private key and services verify with the public key, so a compromised service can't mint tokens.
Authorization: check at the right place
Authentication usually happens once at the edge (the API gateway). Authorization must happen in the service that owns the data, because only it knows whether order 7 belongs to user 42. Missing these object-level checks ("IDOR", broken object level authorization) is the most common API vulnerability.
orders = {7: {"owner": "user-42", "total": 80}, 8: {"owner": "user-99", "total": 15}}
ROLE_PERMISSIONS = {"customer": {"order:read:own"}, "support": {"order:read:any"}}
def can_read(user, roles, order):
perms = set().union(*(ROLE_PERMISSIONS[r] for r in roles))
if "order:read:any" in perms:
return True
return "order:read:own" in perms and order["owner"] == user
checks = [("user-42", ["customer"], 7), ("user-42", ["customer"], 8), ("agent-1", ["support"], 8)]
for user, roles, order_id in checks:
allowed = can_read(user, roles, orders[order_id])
print(f"{user:<8} {str(roles):<13} GET /orders/{order_id} -> {'200' if allowed else '403'}")user-42 ['customer'] GET /orders/7 -> 200
user-42 ['customer'] GET /orders/8 -> 403
agent-1 ['support'] GET /orders/8 -> 200
Defence in depth
- TLS everywhere, including inside the data centre (mTLS between services in a zero-trust network).
- Least privilege: each service gets only the database tables, queues and cloud permissions it needs.
- Rate limiting and account lockout against credential stuffing; CAPTCHAs or proof-of-work for abusive patterns.
- Input validation and parameterised queries against injection; output encoding against XSS.
- Encryption at rest with keys in a KMS; rotate keys and secrets regularly.
- Audit logs of who accessed what, stored where attackers can't delete them.
Tip: Assume breach. Ask of every component: "if an attacker controlled this, what else could they reach?" and shrink that answer.
Test yourself
How should passwords be stored?
- Encrypted with AES
- As a slow, salted hash (bcrypt, scrypt, Argon2, PBKDF2)
- In plain text in a secure database
- As a SHA-256 hash without salt
What is the main drawback of long-lived JWT access tokens?
- They are too large for HTTP headers
- They can't be revoked easily before they expire
- They need a database lookup per request
- They can't hold roles
Where must the check 'does order 7 belong to this user?' happen?
- Only in the browser
- In the service that owns the order data
- Only at the load balancer
- Nowhere, authentication is enough