Restricting incoming requests from hosts
In modern web applications, security is paramount. One crucial aspect of security is ensuring that your application only processes requests from trusted sources. This practice helps to mitigate risks such as Domain Name System (DNS) rebinding attacks, where an attacker tricks a user’s browser into interacting with an unauthorized domain.
FastAPI provides middleware called TrustedHostMiddleware
, which allows you to specify which hosts are considered trusted. Requests from any other hosts will be rejected. This recipe will guide you through setting up and using the TrustedHostMiddleware
class to secure your FastAPI application by accepting requests only from specific hosts.
Getting ready
We will apply the recipe to the middleware_project
application. The application will need to be working with at least one endpoint to test.
How to do it…
Let’s restrict the request to calls coming from localhost. In main.py
...