StackPractices
advanced By Mathias Paulenko

Complete Guide to API Security

Secure your APIs end-to-end: rate limiting, auth, input validation, CORS, injection prevention, gateway patterns, audit logging, and testing.

Introduction

APIs are the primary attack surface of modern applications — every endpoint is an entry point an attacker can reach without touching your frontend, and most are reachable with a single, unauthenticated HTTP request. The OWASP API Security Top 10 exists precisely because API breaches dominate incident reports: broken object-level authorization alone sits behind a large share of data leaks, and it takes one user_id parameter you forgot to check.

The uncomfortable truth about API security: no single control saves you. Rate limiting doesn’t stop a valid-token attacker scraping user 1 through 1,000,000 records. Input validation doesn’t stop an authenticated user editing a field they should never see. Security works as layers — each control catches what the previous one missed — and this guide covers the stack bottom to top: transport and CORS, authentication, rate limiting, input validation, injection prevention, mass assignment, gateway patterns, pagination, audit logging, and how to test it all. Examples use FastAPI + Pydantic v2 because the concepts transfer cleanly to any stack.

Defense in Depth

Think of API security as concentric gates, not a wall:

Defense in depth for APIs: a request passes through CORS and transport checks, authentication and API key validation, rate limiting, input validation and schema checks, then the handler with authorization and mass assignment protection; audit logging and security tests wrap every layer.

Two properties make the layers work. First, each layer fails closed: an expired key, an unknown origin, a malformed body — all return an error before reaching your business logic. Second, the layers are independent: bypassing the rate limiter doesn’t help the attacker if validation and authorization still hold. When you audit your API, walk the layers in order and ask “what does this layer trust about the previous one?” — the answer should be “nothing it didn’t verify”.

Threat Model: What to Protect Against

API abuse clusters into a few shapes:

  • Enumeration attacks — iterating IDs (/users/1, /users/2) to scrape data. Defense: object-level authorization checks (BOLA), rate limiting, pagination caps.
  • Credential stuffing and brute force — hammering auth endpoints with leaked passwords. Defense: strict limits on auth routes, MFA where it matters, logging of failed attempts.
  • Injection — SQL, command, template injection through parameters. Defense: parameterized queries, schema validation, allowlists for dynamic values.
  • Overprivileged writes — mass assignment, privilege escalation by editing role/is_admin fields. Defense: explicit request schemas that exclude sensitive fields.
  • Resource exhaustion — huge bodies, size=999999, expensive queries. Defense: size limits, page caps, query timeouts.
  • Data exposure — returning full objects when three fields would do, verbose errors leaking stack traces. Defense: response DTOs, generic error payloads.

You don’t need a perfect threat model to start — you need the layers in place, then tune to your actual endpoints.

Anatomy of an API Breach

Most real API breaches don’t look like a siege — they look like normal traffic that happens to hit the wrong object. Walk a typical BOLA (broken object-level authorization) incident: the attacker signs up for a free account, gets a real token, and calls GET /api/orders/1 — their order comes back. They change the 1 to a 2. Another customer’s order comes back. No injection, no exploit chain, no alert: every request was authenticated, every response was 200. By the time a partner notices their data on a forum, the attacker has walked every numeric ID across orders, invoices, and support tickets.

What failed wasn’t authentication — it was the layer everyone forgets: checking that the requested object belongs to the authenticated principal. The middleware validated the token; nothing validated that order #2 belonged to that token’s owner. Rate limiting would only have slowed the scrape, not stopped it — 100 requests per minute is still 144,000 records a day.

The lessons generalize: enumerate your object identifiers (orders, users, documents, carts) and for each endpoint ask “who owns this resource, and where is that checked?” If the answer is “the frontend only shows their own” — that’s the bug. BOLA is OWASP API #1 precisely because it’s invisible in traffic and trivial to test: every object endpoint needs one test that asks for another user’s resource and expects a 404 or 403.

Rate Limiting

Without a limit, any endpoint is a free load-test farm and a scraping channel. The three algorithms you actually deploy: token bucket (bursty but bounded — the general default), sliding window (accurate, stricter — payment and auth endpoints), and fixed window (cheapest, boundary-burst-prone). In-memory works for one instance; the moment you scale horizontally you need a shared store like Redis.

Token Bucket Rate Limiter

import time
from collections import defaultdict
from threading import Lock

class TokenBucketRateLimiter:
    def __init__(self, capacity: int, refill_rate: float):
        self.capacity = capacity
        self.refill_rate = refill_rate  # tokens per second
        self.buckets: dict[str, dict] = defaultdict(lambda: {
            "tokens": capacity,
            "last_refill": time.time()
        })
        self.lock = Lock()
    
    def allow_request(self, key: str) -> bool:
        with self.lock:
            bucket = self.buckets[key]
            now = time.time()
            
            # Refill tokens
            elapsed = now - bucket["last_refill"]
            bucket["tokens"] = min(
                self.capacity,
                bucket["tokens"] + elapsed * self.refill_rate
            )
            bucket["last_refill"] = now
            
            if bucket["tokens"] >= 1:
                bucket["tokens"] -= 1
                return True
            return False

# Usage: 100 requests per minute per IP
rate_limiter = TokenBucketRateLimiter(capacity=100, refill_rate=100/60)

from fastapi import FastAPI, Request, HTTPException

app = FastAPI()

@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
    client_ip = request.client.host
    if not rate_limiter.allow_request(client_ip):
        raise HTTPException(
            status_code=429,
            detail="Rate limit exceeded",
            headers={"Retry-After": "60"}
        )
    response = await call_next(request)
    response.headers["X-RateLimit-Limit"] = "100"
    response.headers["X-RateLimit-Remaining"] = str(int(rate_limiter.buckets[client_ip]["tokens"]))
    return response

Two production caveats: in-memory buckets reset on restart and don’t share state across replicas — fine for a single process, wrong for autoscaling. And key on authenticated identity (API key, user id) where possible: IP-based limits punish everyone behind a NAT and let attackers rotate anyway.

Redis-Based Distributed Rate Limiter

import redis
import time

class RedisRateLimiter:
    def __init__(self, redis_client: redis.Redis):
        self.redis = redis_client
    
    def sliding_window(self, key: str, limit: int, window: int) -> bool:
        """Sliding window rate limiter using Redis sorted sets."""
        now = time.time()
        window_start = now - window
        
        pipe = self.redis.pipeline()
        # Remove old entries
        pipe.zremrangebyscore(key, 0, window_start)
        # Add current request
        pipe.zadd(key, {str(now): now})
        # Count current window
        pipe.zcard(key)
        # Set expiry on key
        pipe.expire(key, window)
        
        results = pipe.execute()
        count = results[2]
        
        return count <= limit

# Usage: 1000 requests per hour per API key
def check_rate_limit(api_key: str, redis_client: redis.Redis) -> bool:
    limiter = RedisRateLimiter(redis_client)
    return limiter.sliding_window(
        key=f"rate_limit:{api_key}",
        limit=1000,
        window=3600
    )

Tiered Rate Limiting

class TieredRateLimiter:
    TIERS = {
        "free": {"limit": 100, "window": 3600},       # 100/hour
        "pro": {"limit": 10000, "window": 3600},      # 10k/hour
        "enterprise": {"limit": 100000, "window": 3600}  # 100k/hour
    }
    
    def __init__(self, redis_limiter: RedisRateLimiter):
        self.limiter = redis_limiter
    
    def check(self, api_key: str, tier: str) -> dict:
        config = self.TIERS.get(tier, self.TIERS["free"])
        allowed = self.limiter.sliding_window(
            key=f"rate_limit:{tier}:{api_key}",
            limit=config["limit"],
            window=config["window"]
        )
        
        return {
            "allowed": allowed,
            "limit": config["limit"],
            "window": config["window"],
            "tier": tier
        }

Input Validation

Validation is where untrusted input becomes typed, bounded data. Do it at the schema layer — a dict reaching your handler is a failure. Pydantic v2 (the snippets below use its API: Field constraints and field_validator, replacing the deprecated v1 constr/validator) makes the boundary declarative:

Schema-Based Validation

from pydantic import BaseModel, Field, field_validator
from typing import Optional

class CreateUserRequest(BaseModel):
    username: str = Field(min_length=3, max_length=50, pattern=r'^[a-zA-Z0-9_]+$')
    email: str = Field(min_length=5, max_length=255, pattern=r'^[^@]+@[^@]+\.[^@]+$')
    password: str = Field(min_length=12, max_length=128)
    age: int = Field(ge=13, le=120)
    bio: Optional[str] = Field(default=None, max_length=500)
    
    @field_validator("password")
    @classmethod
    def validate_password_strength(cls, v: str) -> str:
        if not any(c.isupper() for c in v):
            raise ValueError("Password must contain uppercase")
        if not any(c.islower() for c in v):
            raise ValueError("Password must contain lowercase")
        if not any(c.isdigit() for c in v):
            raise ValueError("Password must contain digits")
        if not any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in v):
            raise ValueError("Password must contain special characters")
        return v

@app.post("/api/users")
async def create_user(request: CreateUserRequest):
    # Pydantic validates automatically — invalid data raises 422
    user = User(
        username=request.username,
        email=request.email,
        password_hash=hash_password(request.password),
        age=request.age,
        bio=request.bio
    )
    db.add(user)
    db.commit()
    return {"id": user.id, "username": request.username}

File Upload Validation

import magic

ALLOWED_MIME_TYPES = {
    "image/jpeg": {"jpg", "jpeg"},
    "image/png": {"png"},
    "image/webp": {"webp"},
    "application/pdf": {"pdf"},
}

MAX_FILE_SIZE = 10 * 1024 * 1024  # 10 MB

def validate_file_upload(file_bytes: bytes, filename: str) -> str:
    # Check file size
    if len(file_bytes) > MAX_FILE_SIZE:
        raise ValueError(f"File exceeds {MAX_FILE_SIZE // 1024 // 1024}MB limit")
    
    # Check file extension
    ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
    
    # Detect actual MIME type from content (not from extension)
    mime = magic.from_buffer(file_bytes, mime=True)
    
    if mime not in ALLOWED_MIME_TYPES:
        raise ValueError(f"File type {mime} not allowed")
    
    if ext not in ALLOWED_MIME_TYPES[mime]:
        raise ValueError(f"Extension .{ext} doesn't match MIME type {mime}")
    
    # Check for embedded scripts in images
    if mime.startswith("image/"):
        if b"<script" in file_bytes.lower() or b"<?php" in file_bytes.lower():
            raise ValueError("File contains embedded scripts")
    
    return mime

@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
    content = await file.read()
    mime_type = validate_file_upload(content, file.filename)
    
    # Never trust the user-supplied name — generate your own
    import secrets, os
    ext = os.path.splitext(file.filename)[1].lower()
    safe_filename = f"{secrets.token_hex(8)}{ext}"
    filepath = f"/uploads/{safe_filename}"
    
    with open(filepath, "wb") as f:
        f.write(content)
    
    return {"filename": safe_filename, "mime_type": mime_type}

The pattern that matters: validate content, not claims. python-magic reads magic bytes so malware.exe renamed photo.jpg gets caught; generating your own filename kills path traversal (../../etc/passwd) without any blocklist. If files get served back, store them outside the web root or in object storage, and consider a dedicated scan service for anything non-trivial.

CORS Configuration

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Strict CORS — only allow specific origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://stackpractices.com",
        "https://www.stackpractices.com",
        "https://app.stackpractices.com"
    ],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
    allow_headers=[
        "Authorization",
        "Content-Type",
        "X-Requested-With",
        "X-CSRF-Token"
    ],
    expose_headers=["X-Request-ID", "X-RateLimit-Remaining"],
    max_age=3600  # Cache preflight for 1 hour
)

# Never use allow_origins=["*"] with allow_credentials=True
# This is a security vulnerability — browsers will reject it

CORS is a browser-side control, not a server-side guard — it stops other websites from calling your API with a visitor’s credentials, but a direct attacker with curl ignores it entirely. Common mistakes: wildcard origin + credentials (browsers reject, but many “fix” it by reflecting the Origin header — worse), allowing * on endpoints that take cookies, and forgetting that OPTIONS preflights skip your auth middleware, so don’t gate them.

SQL Injection Prevention

Injection survives because string-built queries keep appearing. The rule has not changed in twenty years: data never concatenates into SQL — it goes in as parameters, always.

# VULNERABLE: String concatenation
def get_user_vulnerable(name: str):
    query = f"SELECT * FROM users WHERE name = '{name}'"
    # Attack: name = "'; DROP TABLE users; --"
    return db.execute(query)

# SAFE: Parameterized queries
def get_user_safe(name: str):
    query = "SELECT * FROM users WHERE name = :name"
    return db.execute(query, {"name": name})

# SAFE: ORM with parameterized queries
def get_user_orm(name: str):
    return db.query(User).filter(User.name == name).first()

# SAFE: SQLAlchemy with explicit parameters
from sqlalchemy import text

def search_users(search_term: str):
    query = text("""
        SELECT id, username, email 
        FROM users 
        WHERE username ILIKE :pattern 
        ORDER BY created_at DESC
        LIMIT 50
    """)
    return db.execute(query, {"pattern": f"%{search_term}%"})

# SAFE: Input sanitization for dynamic queries
def safe_order_by(column: str, allowed_columns: set) -> str:
    """Validate column name for ORDER BY clause."""
    if column not in allowed_columns:
        raise ValueError(f"Invalid sort column: {column}")
    return column

# Usage
allowed = {"username", "email", "created_at", "updated_at"}
sort_column = safe_order_by(request.args.get("sort", "created_at"), allowed)
query = f"SELECT * FROM users ORDER BY {sort_column} DESC"

The last pattern matters more than it looks: parameters cannot bind identifiers (column names, table names, sort direction), so any place you’re tempted to interpolate them — ORDER BY, dynamic filters — needs an explicit allowlist, exactly like safe_order_by above. The ORM doesn’t save you here either; getattr(User, user_column) in a filter is mass assignment’s cousin.

Mass Assignment Protection

Mass assignment — accepting whatever fields the client sends and writing them to the model — is OWASP API #3 and the easiest privilege-escalation bug to ship: an extra "role": "admin" in the JSON and your user updates their own role.

# VULNERABLE: Mass assignment
@app.put("/api/users/{user_id}")
async def update_user(user_id: int, body: dict = Body(...)):
    user = db.query(User).filter(User.id == user_id).first()
    for key, value in body.items():
        setattr(user, key, value)  # Attacker can set role=admin!
    db.commit()
    return user

# SAFE: Explicit field mapping with Pydantic
class UpdateUserRequest(BaseModel):
    username: Optional[str] = Field(default=None, min_length=3, max_length=50)
    email: Optional[str] = Field(default=None, max_length=255)
    bio: Optional[str] = Field(default=None, max_length=500)
    # Note: 'role', 'is_admin', 'password_hash' are NOT included

@app.put("/api/users/{user_id}")
async def update_user(
    user_id: int,
    request: UpdateUserRequest,
    current_user: User = Depends(get_current_user)
):
    if current_user.id != user_id and current_user.role != "admin":
        raise HTTPException(403, "Access denied")
    
    user = db.query(User).filter(User.id == user_id).first()
    
    # Only update allowed fields that were actually sent
    update_data = request.model_dump(exclude_unset=True)
    for key, value in update_data.items():
        setattr(user, key, value)
    
    db.commit()
    return {"id": user.id, "username": user.username}

model_dump(exclude_unset=True) is the second half of the pattern: it includes only fields the client explicitly sent, so a partial update doesn’t null out omitted fields. The schema itself is the allowlist — extra fields in the payload are rejected or ignored before they ever reach setattr.

API Gateway Security

A gateway middleware is the natural place to enforce the outer layers — request size, API keys, rate limits, security headers — once, instead of per-endpoint. Note the signature: @app.middleware("http") decorates a function taking (request, call_next). (For a pure ASGI middleware class the signature is __call__(scope, receive, send) — the two aren’t interchangeable.)

import uuid
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.middleware("http")
async def api_gateway_middleware(request: Request, call_next):
    # 1. Request size limit
    content_length = request.headers.get("content-length")
    if content_length and int(content_length) > 10 * 1024 * 1024:  # 10MB
        return JSONResponse(status_code=413, content={"detail": "Request too large"})
    
    # 2. API key validation (skip public endpoints)
    if request.url.path.startswith("/api/"):
        api_key = request.headers.get("X-API-Key")
        if not api_key:
            return JSONResponse(status_code=401, content={"detail": "Missing API key"})
        
        key_info = validate_api_key(api_key)
        if not key_info:
            return JSONResponse(status_code=401, content={"detail": "Invalid API key"})
        
        # 3. Rate limiting
        rate_check = check_rate_limit(api_key, key_info["tier"])
        if not rate_check["allowed"]:
            return JSONResponse(
                status_code=429,
                content={"detail": "Rate limit exceeded"},
                headers={
                    "Retry-After": str(rate_check["window"]),
                    "X-RateLimit-Limit": str(rate_check["limit"])
                }
            )
    
    # 4. Request ID for tracing
    request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
    request.state.request_id = request_id
    
    # 5. Process request
    response = await call_next(request)
    
    # 6. Add security headers
    response.headers["X-Request-ID"] = request_id
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["Strict-Transport-Security"] = "max-age=31536000"
    
    # 7. Remove sensitive headers from response
    response.headers.pop("Server", None)
    response.headers.pop("X-Powered-By", None)
    
    return response

def validate_api_key(api_key: str) -> dict | None:
    # Look up API key in database — compare hashes, never plaintext
    key_record = db.query(APIKey).filter(
        APIKey.key_hash == hash_api_key(api_key),
        APIKey.is_active == True
    ).first()
    if key_record:
        return {"tier": key_record.tier, "user_id": key_record.user_id}
    return None

Two details worth copying: store API keys as hashes in the database — a leaked table then leaks nothing usable — and return a generic 401 for both missing and invalid keys so existence can’t be probed. If your API is public-facing, consider doing all of this in an actual gateway (Kong, Envoy, NGINX) instead of app middleware, for the reasons in the gatekeeper pattern.

Pagination Security

Unbounded pagination is a self-inflicted DoS: ?size=1000000 is a legal request that returns your entire table per call.

# VULNERABLE: No limit on page size
@app.get("/api/users")
async def list_users(page: int = 1, size: int = 1000):
    # Attacker can request size=1000000 and overwhelm the server
    offset = (page - 1) * size
    return db.query(User).offset(offset).limit(size).all()

# SAFE: Enforce maximum page size
MAX_PAGE_SIZE = 100

@app.get("/api/users")
async def list_users(
    page: int = Query(1, ge=1),
    size: int = Query(20, ge=1, le=MAX_PAGE_SIZE)
):
    offset = (page - 1) * size
    users = db.query(User).offset(offset).limit(size).all()
    total = db.query(User).count()
    
    return {
        "data": [user_to_dict(u) for u in users],
        "pagination": {
            "page": page,
            "size": size,
            "total": total,
            "total_pages": (total + size - 1) // size
        }
    }

# SAFE: Cursor-based pagination (better for large datasets)
import base64
from fastapi import HTTPException

@app.get("/api/users/cursor")
async def list_users_cursor(
    cursor: str | None = Query(default=None),
    size: int = Query(20, ge=1, le=MAX_PAGE_SIZE)
):
    query = db.query(User).order_by(User.id.desc())
    
    if cursor:
        try:
            last_id = int(base64.b64decode(cursor).decode())
        except Exception:
            raise HTTPException(400, "Invalid cursor")
        query = query.filter(User.id < last_id)
    
    users = query.limit(size + 1).all()  # Fetch one extra to check has_more
    has_more = len(users) > size
    users = users[:size]
    
    next_cursor = None
    if has_more and users:
        next_cursor = base64.b64encode(str(users[-1].id).encode()).decode()
    
    return {
        "data": [user_to_dict(u) for u in users],
        "next_cursor": next_cursor,
        "has_more": has_more
    }

Two fixes on the naive version: the cursor decode is wrapped so a malformed cursor returns 400 instead of crashing the request, and cursors encode a position, not a permission — base64 IDs are trivially forgeable, which is fine as long as every row still passes authorization. If the cursor gates anything sensitive, sign it (HMAC) rather than encode it.

Audit Logging

When a breach happens, the first question is “what did they touch?” — and most teams discover they can’t answer it. Log security-relevant events with enough context to reconstruct, never with enough secrets to compound the leak: log the API key prefix, never the key; the user id, never the token.

import json
import logging
import time
from datetime import datetime

class AuditLogger:
    def __init__(self):
        self.logger = logging.getLogger("audit")
        handler = logging.StreamHandler()
        handler.setFormatter(logging.Formatter('%(message)s'))
        self.logger.addHandler(handler)
        self.logger.setLevel(logging.INFO)
    
    def log_api_call(self, request: Request, response, user_id: str | None):
        self.logger.info(json.dumps({
            "timestamp": datetime.now().isoformat(),
            "request_id": getattr(request.state, "request_id", None),
            "method": request.method,
            "path": request.url.path,
            "status_code": response.status_code,
            "user_id": user_id,
            "ip": request.client.host,
            "user_agent": request.headers.get("user-agent", ""),
            "api_key": request.headers.get("x-api-key", "")[:8] + "..." if request.headers.get("x-api-key") else None,
            "response_time_ms": getattr(request.state, "response_time", None)
        }))
    
    def log_security_event(self, event: str, details: dict):
        self.logger.warning(json.dumps({
            "timestamp": datetime.now().isoformat(),
            "event": event,
            "details": details
        }))

audit = AuditLogger()

@app.middleware("http")
async def audit_middleware(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    elapsed_ms = (time.time() - start) * 1000
    
    request.state.response_time = round(elapsed_ms, 2)
    
    # Get user from JWT if present
    user_id = None
    auth_header = request.headers.get("authorization", "")
    if auth_header.startswith("Bearer "):
        try:
            payload = jwt_service.verify_token(auth_header[7:])
            user_id = payload["sub"]
        except Exception:
            pass
    
    audit.log_api_call(request, response, user_id)
    
    # Log suspicious activity
    if response.status_code == 401:
        audit.log_security_event("auth_failure", {
            "ip": request.client.host,
            "path": request.url.path,
            "method": request.method
        })
    elif response.status_code == 403:
        audit.log_security_event("access_denied", {
            "ip": request.client.host,
            "path": request.url.path,
            "user_id": user_id
        })
    
    return response

A burst of auth_failure events from one IP is your credential-stuffing alarm; a user hitting many access_denieds on different resources is the enumeration probe before the breach. Route the security events somewhere with alerting, not just stdout.

API Security Testing

Controls you don’t test are controls you hope work. The good news: most of the tests are small, fast, and run in CI against your normal test client — security regressions get caught like any other bug.

import pytest

class TestAPISecurity:
    def test_sql_injection_in_login(self, client):
        # Test SQL injection in login
        response = client.post("/api/login", json={
            "username": "admin' OR '1'='1",
            "password": "anything"
        })
        assert response.status_code == 401
        assert "token" not in response.json()
    
    def test_mass_assignment(self, client, auth_headers):
        # Test mass assignment protection
        response = client.put("/api/users/me", json={
            "username": "newname",
            "role": "admin",  # Should be ignored
            "is_admin": True   # Should be ignored
        }, headers=auth_headers)
        assert response.status_code == 200
        assert response.json()["role"] != "admin"
    
    def test_rate_limiting(self, client):
        # Test rate limiting
        for i in range(101):
            response = client.get("/api/data")
            if i < 100:
                assert response.status_code == 200
            else:
                assert response.status_code == 429
    
    def test_cors_headers(self, client):
        # Test CORS configuration
        response = client.options(
            "/api/data",
            headers={
                "Origin": "https://evil.com",
                "Access-Control-Request-Method": "GET"
            }
        )
        # Should not allow evil.com
        assert "access-control-allow-origin" not in response.headers or \
               response.headers["access-control-allow-origin"] != "https://evil.com"
    
    def test_authentication_required(self, client):
        # Test that protected endpoints require auth
        response = client.get("/api/users/me")
        assert response.status_code == 401
    
    def test_invalid_token_rejected(self, client):
        # Test invalid JWT
        response = client.get(
            "/api/users/me",
            headers={"Authorization": "Bearer invalid.token.here"}
        )
        assert response.status_code == 401
    
    def test_expired_token_rejected(self, client):
        # Test expired JWT
        expired_token = generate_expired_token()
        response = client.get(
            "/api/users/me",
            headers={"Authorization": f"Bearer {expired_token}"}
        )
        assert response.status_code == 401
    
    def test_pagination_limit_enforced(self, client, auth_headers):
        # Test that page size is capped
        response = client.get(
            "/api/users?size=10000",
            headers=auth_headers
        )
        data = response.json()
        assert len(data["data"]) <= 100  # MAX_PAGE_SIZE

Implementation Order

Security work is never finished, but it’s sequenced — and teams that ship the right layer first recover earlier when the inevitable breach attempt arrives. If you’re starting from zero, the order matters more than the completeness. Week one is the boundary: auth on every non-public endpoint and parameterized queries everywhere — that closes the two highest-frequency breach paths. Week two adds the outer gates: request-size limits, page-size caps, a basic rate limiter, and CORS enumerated to real origins. Week three is where APIs graduate: hashed API keys, explicit update schemas for mass assignment, and the audit log with request_id you can actually query in an incident. Only then do tiered limits, cursor signing, and gateway consolidation pay off — they’re refinements of controls that must already exist. The order isn’t theoretical: it’s the sequence in which each layer makes the next one useful. An audit log before auth just documents unauthenticated requests — useful forensics, but a log of a breach you could have prevented isn’t a security control.

Security Checklist

API Security Checklist:

Authentication:
  [ ] All endpoints require authentication (except public ones)
  [ ] JWT validated (signature, expiration, issuer, audience)
  [ ] API keys hashed in database (never stored plaintext)
  [ ] Failed auth attempts logged and monitored
  [ ] Token expiration enforced

Authorization:
  [ ] Role-based access control on every endpoint
  [ ] Resource ownership checked (user can only access own data)
  [ ] Admin endpoints require admin role
  [ ] Mass assignment prevented (explicit field mapping)

Input Validation:
  [ ] All inputs validated with schema (Pydantic, Zod, Joi)
  [ ] File uploads validated (MIME type, size, content)
  [ ] SQL queries parameterized (no string concatenation)
  [ ] URL parameters validated
  [ ] Request body size limited

Rate Limiting:
  [ ] Rate limiting on all endpoints
  [ ] Tiered limits based on API plan
  [ ] 429 response with Retry-After header
  [ ] Distributed rate limiting (Redis) for multi-instance

CORS:
  [ ] Specific origins allowed (no wildcard with credentials)
  [ ] Allowed methods restricted
  [ ] Allowed headers restricted
  [ ] Preflight cache configured

Logging:
  [ ] All API calls logged with request ID
  [ ] Auth failures logged
  [ ] Access violations logged
  [ ] Response times tracked
  [ ] Sensitive data redacted in logs

Headers:
  [ ] X-Content-Type-Options: nosniff
  [ ] X-Frame-Options: DENY
  [ ] Strict-Transport-Security
  [ ] Server header removed
  [ ] X-Powered-By removed

Authentication in Practice

Two credentials dominate API auth, and they’re complementary rather than competitors. API keys are opaque, long-lived secrets for machines: server-to-server calls, service accounts, CI. They should be treated like passwords — generated with 128+ bits of entropy, stored hashed (the database should hold sha256(key), never the key), scoped to what the caller needs, and rotated. The moment you issue an API key, assume it will eventually leak through logs, a screenshot, or a committed .env — so make leaks survivable: scopes, expirations, IP allowlists for sensitive tiers.

JWTs are for users: signed tokens carrying claims (sub, roles, exp) that let the API authorize without a database lookup on every request. The sharp edges are all in validation — accept only the algorithms you deliberately support (never alg: none, and pin RS256/HS256 rather than negotiating), check exp, iss, and aud, and keep tokens short-lived with refresh rotation. A JWT you can’t revoke is a password you can’t change — for high-stakes actions, check a revocation list or re-verify server-side.

The checklist item “JWT validated (signature, expiration, issuer, audience)” isn’t pedantry: signature confusion (HS256-vs-RS256 downgrade) is a real attack class where the public key becomes the HMAC secret.

Errors and Information Leakage

Error responses are a reconnaissance channel. A 500 that prints psycopg2.errors.UndefinedTable: relation "users" doesn't exist tells the attacker the ORM, the database, and the table names — three free pieces of your schema. Production error handling returns generic messages with an incident ID: {"error": "internal_error", "request_id": "..."} while the real stack trace goes to your private logs with the same ID attached.

Same principle on validation failures: a 422 should say what is wrong with the input, not what else exists — “username already taken” on signup endpoints is an enumeration vector for registered emails (fixable with uniform responses plus email verification flows). And audit your payloads for shape leakage: if /api/users/me returns the full user object because serialization was convenient, you’re leaking password_hash, role, and whatever the model accumulates next year. Response DTOs — explicit output schemas, just like input — are the control; they’re also the cheapest review item: grep your endpoints for return db.query that skips the DTO step.

Versioning and Deprecation Security

Old versions are forgotten attack surface. When /v1/users still runs code written before your auth middleware existed, the v2 hardening protects nobody — the attacker just goes through /v1. Track three rules:

  • Versioned endpoints carry the same controls as current ones. Rate limits, auth, validation apply per-version — never assume “nobody uses v1 anymore” without logs proving it. The usual breach story starts with a legacy endpoint that predates the security layer.
  • Deprecation needs a sunset, not a deletion. Publish a deprecation header (Deprecation + Sunset RFC 8594), alert consumers, monitor traffic, then retire. Deleting without telemetry tells you nothing about who still depends on it — and often resurrects the endpoint under support pressure.
  • Never version security semantics. If v1 and v2 disagree on what “admin” means, one of them is wrong by definition — keep authorization logic shared across versions, only wire format and features differ.

When you do keep parallel versions alive, the security tests above should run against every active version, not just the newest — a fix deployed to v2 that isn’t backported to v1 is documented as a breach-in-waiting.

Best Practices

  • Validate at the boundary with schemas — never let a raw dict reach your handler
  • Store API keys as hashes and rotate them; log only prefixes, never full credentials
  • Use model_dump(exclude_unset=True) for partial updates — the schema is the allowlist
  • Key rate limits on identity (API key/user), not only IP — NATs and proxies make IP unreliable
  • Fail closed: missing key, bad origin, malformed body all return errors before business logic
  • Return minimal response payloads — if the client needs 3 fields, send 3 fields
  • Enforce page-size caps everywhere — unbounded size is a free DoS
  • Strip Server/X-Powered-By and pin nosniff/DENY/HSTS on every response
  • Write one security test per control — they run in the same CI job as the rest

Common Mistakes

  • Wildcard CORS with credentials — browsers reject it and the “fix” (reflecting Origin) opens session theft; enumerate real origins instead
  • Validating by extension or declared type — check magic bytes; evil.exe renamed photo.jpg is the oldest trick
  • Storing API keys in plaintext — one table dump and every key is live; hash them like passwords
  • Trusting user_id from the request — derive identity from the verified token, not from a body/path claim
  • Letting raw dicts into update handlers — mass assignment; the allowlist lives in the request schema
  • Logging full tokens/keys — your log aggregator becomes the credential store; log prefixes only
  • Thinking CORS is a firewall — it’s a browser rule for cross-site scripts; curl doesn’t care

See Also

Further Reading

Frequently Asked Questions

How do I choose between API keys and JWT for authentication?

Use API keys for server-to-server communication and long-lived access (service accounts, CI/CD pipelines). Use JWT for user-facing applications where tokens expire and can be refreshed. API keys are simpler but cannot encode claims or expire automatically. JWTs carry user context (roles, permissions) and expire, but require refresh token management. For public APIs, offer both: API keys for developers and OAuth2/JWT for end-user auth.

What is the best rate limiting algorithm?

Token bucket is the most flexible — it allows bursts up to the bucket capacity while maintaining an average rate. Sliding window provides the most accurate counting but requires more memory. Fixed window is simplest but allows bursts at window boundaries. Use token bucket for user-facing APIs (allows short bursts), sliding window for strict limits (payment APIs), and Redis for distributed rate limiting across multiple instances.

How do I prevent mass assignment vulnerabilities?

Never use setattr or Object.assign with raw user input. Define explicit request schemas (Pydantic, DTOs) that only include fields the user is allowed to update. Exclude sensitive fields like role, is_admin, password_hash, balance from update schemas. Use model_dump(exclude_unset=True) to only update fields that were explicitly provided. Test mass assignment by sending extra fields in requests and verifying they are ignored.

Should I use cursor-based or offset-based pagination?

Use cursor-based pagination for large datasets and real-time feeds. It's faster (no COUNT query) and avoids skipping items when new data is inserted. Use offset-based pagination for small datasets where you need total page count and random page access. Always enforce a maximum page size (e.g., 100 items) regardless of the pagination method to prevent denial of service.

How do I secure file uploads?

Validate the actual MIME type using content inspection (python-magic, file command), not the file extension. Limit file size (e.g., 10MB). Store uploads outside the web root or in object storage (S3, GCS). Generate new filenames — never use the user-supplied filename. Scan for embedded scripts in images. Use a dedicated upload service if processing files (virus scan, image resize). Set Content-Disposition: attachment on download to prevent inline execution.

What security headers should my API return?

Set X-Content-Type-Options: nosniff to prevent MIME sniffing. Set Strict-Transport-Security to enforce HTTPS. Set X-Frame-Options: DENY if your API serves HTML. Remove Server and X-Powered-By headers to avoid fingerprinting. Add Cache-Control: no-store for authenticated responses. Add X-Request-ID for tracing. Do not set Access-Control-Allow-Origin: * with credentials.