Learning outcomes
- Configure strict CORS headers without wildcard vulnerabilities
- Mitigate XSS attacks using Content Security Policy (CSP)
Mental model
Browsers enforce the Same-Origin Policy (SOP) to isolate documents from different domains. CORS (Cross-Origin Resource Sharing) relaxes SOP safely for authorized APIs, while CSP (Content Security Policy) restricts script execution to prevent XSS.
Theory
- CORS Preflight: Browsers send an
OPTIONSHTTP request withAccess-Control-Request-Methodbefore executing non-simple cross-origin requests. - CSP (
Content-Security-Policy): Header directing the browser on allowed script sources, style sources, and image origins (default-src 'self'). - Security Headers:
X-Frame-Options: DENY(clickjacking),X-Content-Type-Options: nosniff(MIME spoofing),Strict-Transport-Security(HSTS).
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Secure CORS Middleware Configuration
ALLOWED_ORIGINS = ["https://fullstackaihub.com", "https://deepmagpie.com"]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
# Custom Security Headers Middleware
@app.middleware("http")
async def add_security_headers(request, call_next):
response = await call_next(request)
response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
return response
Alternatives and trade-offs
- Wildcard CORS (
allow_origins=["*"]): Simple testing setup; catastrophically exposes authenticated APIs to cross-origin data theft if combined with credentials. - Explicit CORS Allowlist: Secure; requires updating server configuration when adding valid client web domains.
Failure modes and misconceptions
Access-Control-Allow-Origin: *with Credentials: Browsers explicitly reject preflight requests ifallow_credentials=Trueis combined with wildcard*origins.- Missing HSTS Headers: Failing to send
Strict-Transport-Securityleaves clients vulnerable to SSL stripping attacks on initial HTTP requests.
Decision scenario
Configure an explicit domain allowlist for CORS middleware and enforce strict CSP and HSTS headers on all public production API endpoints.
Learning outcomes
- Explain browser preflight OPTIONS requests and CORS header validation.
- Construct Content Security Policies (CSP) to block malicious XSS injection.
- Configure mandatory HTTP security headers (
HSTS,X-Frame-Options,X-Content-Type-Options).
Trade-offs
Strict security headers prevent browser vulnerabilities, but misconfigured CSP rules can inadvertently block legitimate external scripts or analytics fonts.
Evidence assessment
Theory and decision mastery
Decision scenario
You are designing a high-concurrency production system requiring reliable execution of cors csp security headers under heavy traffic load.
Which architectural decision ensures maximum resilience, scalability, and system stability?
Primary sources
- FastAPI Framework Architecture & Dependency Injection Specification — Tiangolo, verified 2026-07-22