A simple and lightweight middleware to protect your FastAPI login endpoints from brute-force attacks using per-IP rate limiting with exponential backoff.
- Per-IP login attempt tracking
- Exponential backoff for repeated failed attempts
- Auto-expiry of old IP data (default: 15 minutes)
- Non-intrusive integration via Starlette middleware
- Customizable login path and expiration timeout
pip install fastapi-login-shieldfrom fastapi import FastAPI
from fastapi_login_shield.middleware import LoginShieldMiddleware
app = FastAPI()
# Add the middleware
app.add_middleware(LoginShieldMiddleware, login_path="/login")from fastapi import HTTPException, Request
@app.post("/login")
async def login(request: Request):
# Simulate authentication logic
form = await request.json()
username = form.get("username")
password = form.get("password")
if username != "admin" or password != "secret":
raise HTTPException(status_code=401, detail="Invalid credentials")
return {"message": "Login successful!"}- The middleware intercepts all requests to the specified login path.
- If the response is a failed login (
401or403), it increments the attempt counter for the client IP. - If the count exceeds a threshold (e.g., 3), it applies an exponential delay (
2^countseconds, up to 10 minutes). - If a login succeeds (
2xxresponse), the counter for that IP is reset. - IPs are automatically cleaned from memory if inactive for a configurable duration (default: 900 seconds).
You can customize the login path and expiration time like this:
app.add_middleware(
LoginShieldMiddleware,
login_path="/auth/login",
expire_seconds=600 # expire IP data after 10 minutes
)- This middleware does not block login attempts permanently, it only applies temporary delays.
MIT License