Under The Hood
backend fastapi FastAPI 0.100+ (Starlette Middleware)

CORSMiddleware & TrustedHostMiddleware: Header Validations and Host Header Attacks

Last updated
Prerequisites:
Cross-Origin Resource Sharing (CORS)
HTTP Host Header attacks
  • fastapi
  • cors
  • trusted-host
  • security
  • middleware
  • host-header-attack

Read at your depth

The practical view

`CORSMiddleware` configures Cross-Origin Resource Sharing (CORS) so frontend apps on different domains (e.g. `http://localhost:3000`) can access your API: `app.add_middleware(CORSMiddleware, allow_origins=['https://myfrontend.com'], allow_methods=['*'], allow_headers=['*'])`. `TrustedHostMiddleware` guards against HTTP Host Header attacks by validating that the `Host` header matches an allowed list.

The same idea in other frameworks

fastapi equivalent
`app.add_middleware(CORSMiddleware, allow_origins=[...])`.

Legacy vs modern

Insecure Wildcard CORS vs Secure Origin & Trusted Host Setup

`allow_origins=['*']` with credentials is fundamentally insecure; specific origins and `TrustedHostMiddleware` harden production APIs.

before → after
Insecure Wildcard CORS with Credentials
allow_origins=['*'], allow_credentials=True // ❌ Invalid and insecure configuration
Hardened Production Security Middleware
allow_origins=['https://app.example.com'], app.add_middleware(TrustedHostMiddleware) // ✅ NEW

Interview gotchas

Context

Interviewers test your knowledge of the W3C CORS security specification.

The mechanical answer

The W3C CORS specification strictly forbids combining `Access-Control-Allow-Origin: *` (wildcard) with `Access-Control-Allow-Credentials: true` (cookies / Authorization headers). If a server returns this combination, **the client browser will reject the response and block JavaScript from reading it**. When `allow_credentials=True`, you must specify explicit, non-wildcard origin URLs (e.g. `['https://app.com']`).

Trap

FastAPI will raise a runtime warning or browser requests with cookies will fail if both `allow_origins=['*']` and `allow_credentials=True` are set.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.