Concept lesson

CORS, CSP & Security Headers

Cross-Origin Resource Sharing (CORS), Content Security Policy (CSP), and browser security headers.

lesson
Freshness: current15 min read
Mastery
not started · 0%

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.

Browser Preflight (OPTIONS request)
Server validates Origin header
Match against CORS Allowlist
Return Access-Control-Allow-Origin
Browser permits API response read
Conceptual teaching model synthesized from:FastAPI Framework Architecture & Dependency Injection Specification

Theory

  • CORS Preflight: Browsers send an OPTIONS HTTP request with Access-Control-Request-Method before 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

  1. Access-Control-Allow-Origin: * with Credentials: Browsers explicitly reject preflight requests if allow_credentials=True is combined with wildcard * origins.
  2. Missing HSTS Headers: Failing to send Strict-Transport-Security leaves clients vulnerable to SSL stripping attacks on initial HTTP requests.
Reflect before revealing the guide

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

not-started · 0%
theory0%
decision0%
activityNot mapped
projectNot mapped
1. What is the core architectural principle governing cors csp security headers?
2. What primary operational trade-off must be managed when configuring cors csp security headers?
3. Which failure mode is most commonly observed when cors csp security headers is misconfigured?

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