Password Hashing, Tokens, and Input Validation
Difficulty: Medium-Hard | Companies: Google, Meta, Amazon, Netflix, Stripe
Security questions are rarely trivia. An interviewer wants to see that you know which component is responsible for each guarantee, and that you can explain why the tempting shortcut â a quick SHA-256, a secret in the repository â fails under real attack.
Prerequisites
- !Hashing versus encryption
- !HTTP headers and cookies
- !SQL basics and parameterized queries
What You'll Learn
- 1Explain why password hashing needs a slow, salted algorithm
- 2Choose between session cookies, JWTs, and API keys
- 3Validate untrusted input before it reaches a query or a shell
- 4Manage secrets and security headers without hard-coding anything
Start from the threat, not the library
Defenses only make sense once you name the attacker. A public signup form faces credential stuffing and offline cracking of any database it leaks; an internal admin panel faces privilege escalation by someone who already has a valid session; a file upload endpoint faces path traversal and content spoofing. Writing the threat model down in a few lines before choosing tools keeps the conversation grounded and stops you from bolting on cryptography that solves a problem you do not have.
The map below pairs the failure you will be asked about with the layer that owns the fix. Notice that none of these is solved by "being careful in the handler".
| Threat | What it looks like | Primary defense |
|---|---|---|
| Credential stuffing | Replayed passwords from other breaches | Slow hashing plus rate limiting and MFA |
| SQL injection | User text altering your query shape | Parameterized queries, never string building |
| XSS | Attacker script running in a victim's browser | Output encoding and a strict Content Security Policy |
| Privilege escalation | A normal user reaching an admin action | Server-side authorization on every route |
| Session theft | Stolen cookie replayed elsewhere | Short lifetimes, HttpOnly and Secure flags, rotation |
| Secret leakage | Keys committed or shipped in a client bundle | Environment injection from a vault, never the repo |
| Path traversal | Uploaded filename escaping the upload directory | Allow-list extensions and server-generated names |
Passwords are hashed slowly, on purpose
A password is low-entropy data chosen by a human, so an attacker with the database can try billions of candidates. A fast hash such as SHA-256 makes that cheap; bcrypt and Argon2 deliberately make each verification expensive, and the per-password salt defeats rainbow tables and precomputation. The cost factor is a tunable: high enough to slow an attacker, low enough that your login endpoint still answers in tens of milliseconds.
from passlib.context import CryptContext
pwd = CryptContext(schemes=["bcrypt"], deprecated="auto", bcrypt__rounds=12)
def store_user(email: str, plaintext: str) -> str:
# The salt is generated internally and embedded in the hash string.
return pwd.hash(plaintext)
def check_user(email: str, plaintext: str, hashed: str) -> bool:
if not pwd.verify(plaintext, hashed):
return False
if pwd.needs_update(hashed): # cost factor raised since signup
rehash(email, plaintext)
return True
Two follow-ups are nearly guaranteed. First, why not a faster hash â because the defender must verify one password per login while the attacker verifies millions offline, so latency is the weapon. Second, what about the hash you store when a user never set a password; the answer is to store a sentinel value that verifies nothing, never a hash of an empty string, so that account cannot be logged into by guessing.
Rate limiting belongs next to this code. Locking an account permanently lets an attacker deny service to a real user, so back off exponentially, add a CAPTCHA after a threshold, and prefer counting attempts per account and per source address.
Tokens: JWTs, sessions, and API keys
Each mechanism answers a different question. A session cookie says "this browser is signed in" and keeps state on the server, which makes revocation trivial. A JWT carries claims so that any service can verify identity without a round trip, which suits microservices but makes revocation hard because the token stays valid until it expires. An API key identifies a machine or integration rather than a person and belongs in a header, never in a query string that lands in access logs.
import os
import secrets
from datetime import datetime, timedelta
import jwt
SECRET = os.environ["JWT_SECRET"] # loaded from the environment
ALGO = "HS256"
def issue_token(user_id: str, role: str, minutes: int = 15) -> str:
payload = {"sub": user_id, "role": role, "type": "access",
"iat": datetime.utcnow(),
"exp": datetime.utcnow() + timedelta(minutes=minutes)}
return jwt.encode(payload, SECRET, algorithm=ALGO)
def read_token(token: str) -> dict:
try:
return jwt.decode(token, SECRET, algorithms=[ALGO])
except jwt.ExpiredSignatureError:
raise PermissionError("token expired")
except jwt.InvalidTokenError:
raise PermissionError("token invalid")
def new_api_key() -> str:
return "sk_" + secrets.token_hex(32)
def constant_time_equals(a: str, b: str) -> bool:
import hmac
return hmac.compare_digest(a, b)
The details that earn marks: keep access tokens short-lived and pair them with a refresh token that can be rotated and revoked; verify exp, iss, and aud rather than decoding blindly; use secrets rather than the random module for anything an attacker must not predict; and compare tokens with hmac.compare_digest so response timing does not leak a prefix.
Validate input, parameterize queries
Validation and authorization are separate jobs, and confusing them is a common source of holes: checking that a field is a valid integer does nothing to prove the caller may read that row. Validate shape and range at the boundary, then enforce permissions against the loaded object.
For injection, the story is simpler than it used to be. Never build a query with an f-string or % formatting â hand the SQL with placeholders to the driver and pass values separately, so the database parses the statement before it ever sees the data.
import re
import sqlite3
ALLOWED_EXT = {"csv", "png", "pdf"}
def safe_filename(raw: str) -> str:
name = os.path.basename(raw.replace("\\", "/"))
if ".." in name or not re.fullmatch(r"[A-Za-z0-9._-]{1,120}", name):
raise ValueError("unsafe filename")
ext = name.rsplit(".", 1)[-1].lower()
if ext not in ALLOWED_EXT:
raise ValueError("extension not allowed")
return f"{secrets.token_hex(8)}.{ext}"
def find_orders(conn, email: str, minimum: int):
cursor = conn.execute(
"SELECT id, total FROM orders WHERE email = ? AND total >= ?",
(email, minimum),
)
return cursor.fetchall()
def run_report(conn, sort_column: str):
# Identifiers cannot be parameterized, so map to a fixed allow-list.
columns = {"created": "created_at", "total": "total"}
if sort_column not in columns:
raise ValueError("unsupported sort")
return conn.execute(
f"SELECT id FROM orders ORDER BY {columns[sort_column]}"
)
The allow-list pattern in run_report is the one place string interpolation is acceptable, because the value is chosen from a dictionary you wrote rather than from the request. Escape-based defenses and keyword blocklists fail the moment the input encoding changes; structural separation does not.
Secrets, configuration, and headers
Secrets belong in the environment or a managed vault, injected at deploy time, with rotation scripted and tested. Committed keys are not a hypothetical: repositories are scanned constantly, and a credential in git history stays live until you revoke it, so revoking first and cleaning history second is the right order.
Response headers close off whole categories of attack at very low cost. Strict-Transport-Security refuses plaintext on future requests, X-Content-Type-Options: nosniff stops MIME sniffing, Content-Security-Policy limits scripts to origins you control, and X-Frame-Options blocks clickjacking. Set them once in middleware so no individual handler can forget.
Logging deserves a warning of its own: never write passwords, tokens, or full card numbers to a log, because logs travel to third-party aggregators with far weaker access control than your database. Log identifiers and hashes, redact at the formatter, and audit what your logging library captures by default, including exception tracebacks that may embed local variables.
Test the defenses like an attacker
A security control with no test is a rumor. Assert that a wrong password returns the same generic error as an unknown account so you do not disclose which emails are registered; assert that an expired token is refused; assert that a filename containing a traversal sequence is rejected before any filesystem call; and assert that admin routes return 403 for a non-admin token even when the object exists. Those five tests catch the regressions that matter most, because the day someone "simplifies" the authorization check is the day the hole reappears.
Common Mistakes
Hashing passwords with MD5, SHA-1, or plain SHA-256
Fix: Use bcrypt, scrypt, or Argon2 with a work factor you have tuned, and re-hash when the factor rises.
Building SQL with f-strings and escaping quotes by hand
Fix: Pass placeholders to the driver and let the database parse the statement before it sees any value.
Trusting the client because the UI hid a button
Fix: Re-check authorization on the server for every request, against the specific object being accessed.
Storing JWT secrets or API keys in the repository
Fix: Load them from the environment or a vault, revoke anything ever committed, and script rotation.
Best Practices
- Write a two-line threat model before choosing a security mechanism
- Use secrets and hmac.compare_digest for anything an attacker must not predict
- Keep access tokens short-lived with a rotating refresh token for revocation
- Set security headers once in middleware rather than per handler
- Redact credentials at the logging formatter, not at each call site
- Add regression tests for expired tokens, traversal filenames, and denied roles
Interview Questions
Q1: Why is bcrypt preferred over SHA-256 for passwords?
bcrypt is deliberately slow and salted, so an attacker holding the database cannot test billions of guesses per second or precompute rainbow tables.
Q2: Session cookies or JWTs for a web app?
Cookies with server-side state when you need instant revocation; JWTs when independent services must verify identity without a shared store, accepting that tokens stay valid until expiry.
Q3: How do you prevent SQL injection in Python?
Parameterized queries with placeholders for values, and an allow-list mapping for identifiers such as sort columns, never string concatenation of user input.
Q4: Where should application secrets live?
In a vault or environment variable injected at deploy time, never in git, and any leaked credential is revoked before history is cleaned.
Q5: What is the difference between authentication and authorization?
Authentication establishes who you are; authorization decides what that identity may do, and it must be enforced server-side on every request.
Q6: How do you handle a file upload safely?
Allow-list extensions, generate a server-side random name, reject traversal sequences, store outside the web root, and verify content type independently of the client's claim.
Key Takeaways
- Name the threat first; each attack has a layer that owns the fix
- Password hashing is intentionally slow, salted, and upgraded over time
- JWTs trade easy verification for hard revocation â pick consciously
- Parameterize queries and allow-list identifiers; never interpolate user text
- Secrets come from the environment, are rotated, and are redacted from logs
- Security guarantees deserve regression tests so refactors cannot silently drop them