Python / ASGI · Starlette + Credentials

FastAPI CORSMiddleware with Credentials, Cookies & Explicit Origins

Fix FastAPI/Starlette CORS failures when allow_credentials=True: why allow_origins=['*'] breaks cookies/Auth headers, middleware ordering, and preflight 500 error masking.

Zero Telemetry · Strict CSP (connect-src 'none')

CORS Policy & Preflight Controls

Access-Control-Allow-Methods
Simulate Browser Preflight Request (OPTIONS)
CORS Security & Fetch Spec Linter
100 / 100
PASS

Pass: 3 · Warnings: 0 · Errors: 0

CORS-002: Strict origin allowlist (2 origins) PASS
https://app.example.com, https://studio.example.com
CORS-004: Vary: Origin cache safety enabled PASS
Prevents CDN/proxy cache poisoning across distinct allowed origins.
CORS-005: Access-Control-Max-Age (7200s) within Chromium 7200s cap PASS
Avoids unnecessary OPTIONS preflight round-trips while honoring cross-browser cache ceilings.
Simulated Preflight Response
# Simulated Browser Preflight: OPTIONS /api/v1/resource
# Request Origin: https://app.example.com | Method: POST | Headers: Authorization, Content-Type
# Browser Verdict: ALLOWED (HTTP 204 No Content)

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type, X-Requested-With, Idempotency-Key
Access-Control-Expose-Headers: X-Request-Id, X-RateLimit-Remaining
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 7200
Vary: Origin

Copy-Paste Runtime Configs (6 Stacks)

FastAPI (main.py)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com","https://studio.example.com"],
    allow_credentials=True,
    allow_methods=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],
    allow_headers=["Authorization","Content-Type","X-Requested-With","Idempotency-Key"],
    expose_headers=["X-Request-Id","X-RateLimit-Remaining"],
    max_age=7200,
)
Live API & Edge Audit Zero-Upload SpecDiff

Harden your live domain headers, OpenAPI schemas & AEO discovery

Test your deployed domain's security headers, HSTS, CSP & DMARC live on ReadyCheck, diff OpenAPI contracts & OWASP API Top 10 risks in SpecDiff, or deploy all 9 production configs in minutes with the $49 ReadyCheck Fix Pack.

Protocol Rules & Header Reference

Rule / Header Production Value Behavior & Gotchas
allow_origins Explicit list (never ['*'] with credentials) Starlette reflects request Origin if ['*'] + allow_credentials=True in older versions or breaks spec
allow_credentials True (only with explicit origins) Required for fetch(..., { credentials: 'include' }) and cross-site cookies
Middleware Order Add CORSMiddleware LAST (outermost) Starlette executes middlewares in LIFO order; outermost wraps error handlers
max_age 7200 (default 600s in Starlette) Increasing from 600s to 7200s cuts OPTIONS preflight volume

FastAPI Production CORSMiddleware Configuration

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

app = FastAPI(title="Acme API")

ALLOWED_ORIGINS = [
    "https://app.example.com",
    "https://studio.example.com",
]

# Register CORSMiddleware LAST so it runs FIRST (outermost) and wraps error responses
app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=["Authorization", "Content-Type", "Idempotency-Key"],
    expose_headers=["X-Request-Id", "X-RateLimit-Remaining"],
    max_age=7200,
)

@app.get("/health")
async def health():
    return {"ok": True}

FastAPI Raw-Body Webhook Verification (Avoid JSON Re-Serialization)

webhook_route.py
import hmac, hashlib
from fastapi import APIRouter, Request, HTTPException

router = APIRouter()

@router.post("/webhooks/creem")
async def creem_webhook(request: Request):
    raw_body = await request.body()  # Exact bytes! Never await request.json() before HMAC!
    sig = request.headers.get("creem-signature", "")
    expected = hmac.new(b"whsec_...", raw_body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(sig, expected):
        raise HTTPException(status_code=401, detail="Invalid signature")
    return {"received": True}

Key Engineering Takeaways

  • FastAPI wraps Starlette's CORSMiddleware: if allow_origins=['*'] and allow_credentials=True are combined, browsers reject the wildcard credentialed response (or Starlette falls back to reflecting arbitrary Origin headers — a critical CSRF risk).
  • Always register CORSMiddleware after custom auth/logging middlewares so unhandled exceptions or 401 responses still carry Access-Control-Allow-Origin headers.
  • Using allow_origin_regex='https://.*\.example\.com' safely handles preview deployments when anchored strictly with ^https://...$.

Common Production Pitfalls to Avoid

  • Leaving allow_origin_regex=r'https://.*example\.com' unanchored allows https://evil-example.com.
  • Reading await request.json() and calling json.dumps() before computing webhook HMAC breaks signatures whenever whitespace or key ordering differs.
  • Forgetting to list custom headers like X-API-Key or Idempotency-Key in allow_headers when allow_credentials=True (wildcard '*' headers are ignored in credentialed requests).

More CORS & Webhook Signature Guides

← Back to CORS & Webhook HMAC Debugger Hub · OpenAPI OWASP API Top 10 & MCP Scorer → · SBOM & Sigstore Validator → · HTTP Security Headers & CSP →

Frequently Asked Questions

Why does FastAPI return 'CORS error' when my route raises an unhandled 500 exception?

Starlette's ServerErrorMiddleware sits outside user middlewares by default and returns 500 without CORS headers. Catch domain exceptions cleanly and register CORSMiddleware outermost.

Can I use allow_origins=['*'] with Bearer Authorization headers?

Only if credentials: 'omit'/'same-origin' and allow_credentials=False! Even then, explicit origin allowlists are strongly recommended for authenticated APIs.

How do I test my FastAPI CORS policy before deploying?

Configure your origins and headers in the CORS Preflight Linter above to verify simulated 204 preflight output and catch Fetch spec violations.