What if a simple middleware could protect your app from sneaky fake hosts without extra code?
Why Trusted host middleware in FastAPI? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you run a web app and want to make sure only requests from your official website or trusted domains get through.
You try to check the request's host manually in every route handler.
Manually checking hosts everywhere is tiring and easy to forget.
It can lead to security holes if a route misses the check.
Also, it clutters your code and slows down development.
Trusted host middleware automatically blocks requests from unapproved hosts before they reach your app.
This keeps your app safe and your code clean.
if request.headers.get('host') not in allowed_hosts: return Response(status_code=400)
from fastapi.middleware.trustedhost import TrustedHostMiddleware app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'www.example.com'])
You can focus on building features while the middleware guards your app from bad hosts.
A company wants to ensure only requests from their official domains reach their API, blocking all others automatically.
Manual host checks are error-prone and repetitive.
Trusted host middleware centralizes and automates host validation.
This improves security and keeps your code simple.
Practice
TrustedHostMiddleware in FastAPI?Solution
Step 1: Understand middleware role
TheTrustedHostMiddlewareis designed to filter incoming requests based on their host header.Step 2: Identify its security purpose
It blocks requests from hosts not explicitly allowed to protect against host header attacks.Final Answer:
To block requests from hosts not in the allowed list -> Option AQuick Check:
TrustedHostMiddleware blocks unknown hosts = D [OK]
- Confusing it with authentication middleware
- Thinking it speeds up app performance
- Assuming it manages database connections
TrustedHostMiddleware to a FastAPI app?Solution
Step 1: Recall FastAPI middleware syntax
FastAPI usesapp.add_middleware()with the middleware class and keyword arguments.Step 2: Check correct argument name
The correct argument for allowed hosts isallowed_hosts, nothostsorallowed.Final Answer:
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com']) -> Option BQuick Check:
Use add_middleware with allowed_hosts = C [OK]
- Using wrong method like app.use()
- Passing 'hosts' instead of 'allowed_hosts'
- Incorrect argument names like 'allowed'
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'localhost'])
@app.get('/')
def read_root():
return {'message': 'Hello World'}Solution
Step 1: Check allowed hosts list
The allowed hosts are 'example.com' and 'localhost'. 'malicious.com' is not in this list.Step 2: Understand middleware behavior on unknown hosts
TrustedHostMiddleware blocks requests from hosts not in the allowed list by returning a 400 error.Final Answer:
The request will be blocked with a 400 Bad Request error -> Option DQuick Check:
Unknown host causes 400 error = A [OK]
- Assuming the request passes through
- Thinking the app crashes on unknown hosts
- Believing the request is redirected automatically
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts='example.com')
@app.get('/')
def home():
return {'msg': 'Welcome'}Solution
Step 1: Check allowed_hosts argument type
Theallowed_hostsparameter expects a list of strings, but a single string was given.Step 2: Understand impact of wrong type
Passing a string instead of a list will cause the middleware to treat each character as a host, leading to incorrect behavior or errors.Final Answer:
allowed_hosts should be a list, not a string -> Option CQuick Check:
allowed_hosts must be list = A [OK]
- Passing a single string instead of list
- Thinking route functions must be async
- Assuming import is incorrect without error
example.com and also from localhost. Which allowed_hosts list correctly configures TrustedHostMiddleware for this?Solution
Step 1: Understand wildcard usage in allowed_hosts
TrustedHostMiddleware supports wildcards like*.example.comto allow all subdomains.Step 2: Check each option for correct wildcard syntax
['*.example.com', 'localhost'] uses'*.example.com'which correctly matches all subdomains; others use incorrect patterns.Final Answer:
['*.example.com', 'localhost'] -> Option AQuick Check:
Use '*.example.com' for subdomains = B [OK]
- Using 'example.com/*' which is invalid
- Using '*example.com' missing dot after *
- Not using wildcard for subdomains
