Security best practices in FastAPI

Difficulty: Advanced

Question

What security best practices should you follow when building a FastAPI application?

Answer

1. HTTPS everywhere - Terminate SSL at the reverse proxy. Use `--forwarded-allow-ips` to trust proxy headers.

2. Security headers - Add via middleware: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Strict-Transport-Security`, `Content-Security-Policy`.

3. CORS - Whitelist specific origins, never use `allow_origins=['*']` with `allow_credentials=True`.

4. Input validation - Pydantic models handle this, but sanitize HTML output and use parameterized DB queries.

5. Secrets management - Use `pydantic-settings` with env vars. Never commit secrets to code.

6. Rate limiting - Prevent brute force and DDoS with SlowAPI or API gateway.

7. SQL injection - Use ORM (SQLAlchemy) or parameterized queries. Never interpolate user input into SQL strings.

8. Dependency updates - Regularly update dependencies. Use `pip-audit` or `safety` to check for CVEs.

Code examples

Security headers middleware

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

# Restrict allowed hosts
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])

# Strict CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

# Custom security headers
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
    return response

Key points

Concepts covered

security headers, HTTPS, CSRF, input sanitization, secrets