- CSRF-Token pro Session, Pflicht-Header X-CSRF-Token bei POST/PUT/PATCH/DELETE - Middleware lehnt zustandsändernde Requests mit fremdem Origin ab - Sperre nach 5 Fehlversuchen pro Benutzername in 15 Minuten (HTTP 429) - IP-Sperre vorbereitet, per LOGIN_IP_LOCKOUT aktivierbar - stündliches Aufräumen abgelaufener Sessions und alter Login-Versuche Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
27 lines
1.1 KiB
Python
27 lines
1.1 KiB
Python
from starlette.datastructures import Headers
|
|
from starlette.responses import JSONResponse
|
|
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
|
|
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
|
|
|
|
|
class OriginCheckMiddleware:
|
|
"""Reject state-changing requests whose Origin header is not an allowed origin.
|
|
|
|
Browsers always send Origin on cross-site POST/PUT/PATCH/DELETE. Requests without
|
|
the header come from non-browser clients and are left to the authentication layer.
|
|
"""
|
|
|
|
def __init__(self, app: ASGIApp, allowed_origins: list[str]) -> None:
|
|
self.app = app
|
|
self.allowed_origins = frozenset(allowed_origins)
|
|
|
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
if scope["type"] == "http" and scope["method"] not in SAFE_METHODS:
|
|
origin = Headers(scope=scope).get("origin")
|
|
if origin is not None and origin.rstrip("/") not in self.allowed_origins:
|
|
response = JSONResponse({"detail": "Ungültige Herkunft (Origin)."}, 403)
|
|
await response(scope, receive, send)
|
|
return
|
|
await self.app(scope, receive, send)
|