Installation¶
Install flaskapi-guard using pip:
Note: Ensure you have Python 3.10 or higher installed.
Prerequisites¶
Before using flaskapi-guard's country filtering features, obtain an IPInfo token:
- Visit IPInfo's website to create a free account.
- After signing up, you'll receive an API token.
- The free tier includes:
- Up to 50,000 requests per month.
- Access to IP to Country database.
- Daily database updates.
- IPv4 & IPv6 support.
Note: The IPInfo token is only required when using the country filtering features (blocked_countries, whitelist_countries and/or block_cloud_providers).
Usage Example:
from flask import Flask
from flaskapi_guard import FlaskAPIGuard
from flaskapi_guard.models import SecurityConfig
from flaskapi_guard.handlers.ipinfo_handler import IPInfoManager
app = Flask(__name__)
config = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"), # NOTE: Required when using country blocking
enable_redis=True, # Enabled by default, disable to use in-memory storage
redis_url="redis://localhost:6379/0",
redis_prefix="prod:security:",
whitelist=["192.168.1.1", "2001:db8::1"],
blacklist=["10.0.0.1", "2001:db8::2"],
blocked_countries=["AR", "IT"],
blocked_user_agents=["curl", "wget"],
auto_ban_threshold=5,
auto_ban_duration=86400,
custom_log_file="security.log",
)
FlaskAPIGuard(app, config=config)
Note: When Redis is disabled: - Rate limiting and IP bans become instance-local - Cloud provider IP ranges refresh every hour - Penetration patterns reset on app restart
Secure Proxy Configuration¶
If your application is behind a proxy or load balancer, configure trusted proxies:
config = SecurityConfig(
# Security configuration for proxies
trusted_proxies=["10.0.0.1", "192.168.1.0/24"], # Only trust specific IPs/ranges
trusted_proxy_depth=1, # Default proxy depth
trust_x_forwarded_proto=True, # Trust X-Forwarded-Proto from trusted proxies
# Other config options...
)
This prevents IP spoofing attacks via X-Forwarded-For header manipulation.