21 lines
635 B
Python
21 lines
635 B
Python
import secrets
|
|
|
|
from fastapi import HTTPException, Request, status
|
|
|
|
|
|
CSRF_COOKIE_NAME = "csrf_token"
|
|
CSRF_FORM_FIELD = "csrf_token"
|
|
|
|
|
|
def ensure_csrf_cookie(request: Request) -> str:
|
|
token = request.cookies.get(CSRF_COOKIE_NAME)
|
|
if token:
|
|
return token
|
|
return secrets.token_urlsafe(32)
|
|
|
|
|
|
def validate_csrf(request: Request, form_token: str) -> None:
|
|
cookie_token = request.cookies.get(CSRF_COOKIE_NAME)
|
|
if not cookie_token or not form_token or not secrets.compare_digest(cookie_token, form_token):
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="CSRF-Validierung fehlgeschlagen.")
|