Secure Your FastAPI Applications with fastapi-guard
In today’s world, web application security is more important than ever. With the increasing number of cyber threats, it’s crucial to have robust security measures in place. That’s where fastapi-guard comes in. This powerful security library for FastAPI provides middleware to control IPs, log requests, and detect penetration attempts, offering seamless integration with FastAPI to protect against various security threats.
Prerequisites
Before using fastapi-guard, you’ll need to obtain an IPInfo token:
- Visit [IPInfo’s website](https://ipinfo.io/signup) to create a free account
2. After signing up, you’ll receive an API token
3. The free tier includes:
- Up to 50,000 requests per month
- Access to IP to Country database
- Daily database updates
- IPv4 & IPv6 support
Key Features
fastapi-guard comes packed with a variety of features to enhance the security of your FastAPI applications:
- IP Whitelisting and Blacklisting: Control access based on IP addresses.
- User Agent Filtering: Block requests from specific user agents.
- Rate Limiting: Limit the number of requests from a single IP.
- Automatic IP Banning: Automatically ban IPs after a certain number of suspicious requests.
- Penetration Attempt Detection: Detect and log potential penetration attempts.
- Custom Logging: Log security events to a custom file.
- CORS Configuration: Configure CORS settings for your FastAPI application.
- Cloud Provider IP Blocking: Block requests from cloud provider IPs (AWS, GCP, Azure).
- IP Geolocation: Use IPInfo.io API to determine the country of an IP address
Installation
Getting started with fastapi-guard is easy. You can install it using pip:
pip install fastapi-guard
Basic Setup
To use fastapi-guard, you need to configure the middleware in your FastAPI application. Here’s a basic example:

Advanced Usage
Custom Request Check
You can define a custom function to perform additional checks on the request using the custom_request_check option.

Custom Response Modifier
You can define a custom function to modify the response before it’s sent using the custom_response_modifier option.

Detailed Configuration Options
The SecurityConfig class defines the structure for security configuration, including IP whitelists and blacklists, blocked countries, blocked user agents, rate limiting, automatic IP banning, IPInfo settings, HTTPS enforcement, custom hooks, CORS settings, and blocking of cloud provider IPs.
Attributes
- ipinfo_token: str — The IPInfo API token required for IP geolocation functionality
- whitelist: Optional[List[str]] — A list of IP addresses or ranges that are always allowed
- blacklist: List[str] — A list of IP addresses or ranges that are always blocked
- blocked_countries: List[str] — A list of country codes whose IP addresses should be blocked
- blocked_user_agents: List[str] — A list of user agent strings or patterns that should be blocked
- auto_ban_threshold: int — The threshold for auto-banning an IP address
- auto_ban_duration: int — The duration in seconds for which an IP address should be banned
- custom_log_file: Optional[str] — The path to a custom log file for logging security events
- custom_error_responses: Dict[int, str] — A dictionary of custom error responses
- rate_limit: int — The maximum number of requests allowed per minute from a single IP
- enforce_https: bool — Whether to enforce HTTPS connections
- custom_request_check: Optional[Callable] — A custom function for additional request checks
- custom_response_modifier: Optional[Callable] — A custom function to modify responses
- enable_cors: bool — Whether to enable CORS
- cors_allow_origins: List[str] — A list of allowed origins
- cors_allow_methods: List[str] — A list of allowed methods
- cors_allow_headers: List[str] — A list of allowed headers
- cors_allow_credentials: bool — Whether to allow credentials
- cors_expose_headers: List[str] — A list of exposed headers
- cors_max_age: int — Maximum age for preflight requests
- block_cloud_providers: Optional[Set[str]] — Cloud providers to block
Conclusion
fastapi-guard is a comprehensive security library for FastAPI that provides a wide range of features to protect your applications from various security threats. Whether you need IP whitelisting and blacklisting, user agent filtering, rate limiting, or penetration attempt detection, fastapi-guard has you covered. Install it today and secure your FastAPI applications with ease.
For more information and to contribute, visit the GitHub repository.