0
0
FastAPIframework~5 mins

Trusted host middleware in FastAPI

Choose your learning style9 modes available
Introduction

Trusted host middleware helps your app accept requests only from safe website addresses. It blocks requests from unknown or harmful sources.

When you want to stop fake or harmful requests from unknown websites.
When your app should only respond to specific domain names you control.
To protect your app from host header attacks.
When deploying your app behind proxies or load balancers and you want to ensure correct host validation.
Syntax
FastAPI
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["example.com", "www.example.com"]
)

The allowed_hosts list contains the hostnames your app trusts.

Use "*" to allow all hosts, but this disables protection.

Examples
Only requests with host header myapp.com are accepted.
FastAPI
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["myapp.com"]
)
Accepts requests from local development addresses.
FastAPI
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["localhost", "127.0.0.1"]
)
Allows all hosts (not recommended for production).
FastAPI
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"]
)
Sample Program

This FastAPI app only accepts requests where the host header is "example.com" or "www.example.com". Other hosts get blocked.

FastAPI
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import PlainTextResponse

app = FastAPI()

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["example.com", "www.example.com"]
)

@app.get("/")
async def read_root():
    return PlainTextResponse("Hello from trusted host!")
OutputSuccess
Important Notes

TrustedHostMiddleware returns a 400 error if the host is not allowed.

Make sure to include all domain variants your app uses (with and without www).

Use this middleware early in your middleware stack for best protection.

Summary

Trusted host middleware blocks requests from unknown hosts.

Configure it with a list of allowed hostnames.

It helps protect your app from host header attacks.