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)