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
`app.add_middleware(CORSMiddleware, allow_origins=[...])`.`app.enableCors({ origin: 'https://app.com' })`.`@CrossOrigin` or `CorsConfigurationSource` in Spring Security.`app.use(cors({ origin: 'https://app.com' }))`.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.
allow_origins=['*'], allow_credentials=True // ❌ Invalid and insecure configurationallow_origins=['https://app.example.com'], app.add_middleware(TrustedHostMiddleware) // ✅ NEWInterview 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.
Context
Checks knowledge of web security and HTTP Host header attacks.
The mechanical answer
It prevents **HTTP Host Header Attacks**. Attackers can send arbitrary `Host: evil.com` headers to a web server. If your application generates password reset links using `request.base_url` or uses host headers in caching proxies, the attacker can poison cache entries or trick the server into sending password reset emails containing phishing links pointing to `evil.com`. `TrustedHostMiddleware` rejects any request with an unrecognized `Host` header with a 400 Bad Request.
Trap
Always include `localhost` and your staging/production domains in `allowed_hosts`.