12. Security Essentials
Defend in depth: validate inputs, protect secrets, and use safe crypto primitives.
Question: What are the most critical security practices for a Python backend developer?
Answer: The most critical practices are to never trust user input, handle secrets securely, and keep dependencies up-to-date.
Explanation:
Validate Inputs: Always validate and sanitize all data from users to prevent injection attacks. Use ORM-bound parameters instead of raw SQL strings.
Handle Secrets: Never hardcode secrets in source code. Load them from environment variables or a secret management system. Never log secrets or personally identifiable information (PII).
Passwords: Use a strong, adaptive hashing algorithm like
bcrypt
orargon2
to store password hashes.Dependencies: Regularly scan for and update dependencies to patch known vulnerabilities.
Question: How does an ORM help prevent SQL injection attacks?
Answer: ORMs prevent SQL injection by using parameterized queries (or prepared statements) instead of string formatting to construct SQL queries.
Explanation: A SQL injection attack occurs when an attacker provides malicious input (like ' OR 1=1; --
) that gets concatenated into a raw SQL string, altering the query's logic. An ORM avoids this by separating the SQL query logic from the user-provided data. The data is sent to the database driver as separate parameters, not as part of the query string itself. The driver then safely handles the data, treating it as literal values rather than executable code.
Question: What are CORS and CSRF, and how do they apply to Python backends?
Answer: CORS is a browser policy regulating cross-origin requests; CSRF is a forged cross-site state-changing request. Token-based APIs without cookies are typically not CSRF-vulnerable; cookie-based sessions need CSRF protections. Always configure CORS explicitly.
Explanation: In FastAPI, add CORSMiddleware
to allow specific origins, headers, and methods.
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
Question: What are common JWT pitfalls and mitigations?
Answer: Short TTLs with refresh, key rotation (kid
), clock-skew tolerance, audience/issuer checks, and deny lists for high-risk revocation.
Explanation: Never accept alg=none
; avoid sensitive data in JWT payloads.
Question: When should you use
secrets
instead ofrandom
? How to compare secrets safely?
Answer: Use secrets
for cryptographic randomness; compare secrets with hmac.compare_digest
to avoid timing attacks.
import secrets, hmac
token = secrets.token_urlsafe(32)
assert hmac.compare_digest(token, token)