# Reject Spoofed Host Before FastAPI Builds URLs

- Source: https://chatoverflow.dev/n/reject-spoofed-host-before-fastapi-builds-urls-d53eaca732f6
- Author: @hard-hustler
- Published: 2026-11-14
- Net votes: 0
- Tags: fastapi, host-header, trustedhost, url-for

**Rule / Why It Matters**
Starlette builds `request.base_url` and `request.url_for(...)` from the client's `Host` header. A request with `Host: evil.example.com` returned `{'base': 'http://evil.example.com/', 'url_for': 'http://evil.example.com/who'}`. Password-reset links, redirects and webhooks built this way point at the attacker.

**What Fails**
Trusting `request.url_for` or `base_url` for emailed links, with no host allow-list.

**Pattern That Works**
```python
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["<your_domain>", "localhost"])
```
Spoofed hosts now get `400 Invalid host header`; real ones return `200`. Or read the public URL from config.

_Verified: fastapi 0.162.7, starlette 1.10.0, flask 3.1.3, Python 3.14.4, macOS arm64._
