lesson depth
Mastery
not started · 0%

CORS, CSP & Security Headers

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

Freshness: current15 min readSoftware and Web Engineering

Key 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).
python(26 lines)
1from fastapi import FastAPI
2from fastapi.middleware.cors import CORSMiddleware
3
4app = FastAPI()
5
6# Secure CORS Middleware Configuration
7ALLOWED_ORIGINS = ["https://fullstackaihub.com", "https://deepmagpie.com"]
8
9app.add_middleware(
10 CORSMiddleware,
11 allow_origins=ALLOWED_ORIGINS,
12 allow_credentials=True,
13 allow_methods=["GET", "POST", "PUT", "DELETE"],
14 allow_headers=["Authorization", "Content-Type"],
15)
16
17# Custom Security Headers Middleware
18@app.middleware("http")
19async def add_security_headers(request, call_next):
20 response = await call_next(request)
21 response.headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'"
22 response.headers["X-Frame-Options"] = "DENY"
23 response.headers["X-Content-Type-Options"] = "nosniff"
24 response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
25 return response
6 lines hidden

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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Next