Skip to content

Commit 20c5839

Browse files
committed
fix: in flexible mode, pre-verify token location
1 parent 8454a52 commit 20c5839

File tree

1 file changed

+10
-2
lines changed
  • src/fastapi_csrf_protect/flexible

1 file changed

+10
-2
lines changed

src/fastapi_csrf_protect/flexible/core.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
### Third-party packages ###
2020
from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer
2121
from pydantic import create_model
22-
from starlette.datastructures import Headers
22+
from starlette.datastructures import Headers, UploadFile
2323
from starlette.requests import Request
2424
from starlette.responses import Response
2525

@@ -174,7 +174,15 @@ async def validate_csrf(
174174
time_limit = time_limit or self._max_age
175175
token: Optional[str] = self.get_csrf_from_headers(request.headers)
176176
if not token:
177-
token = self.get_csrf_from_body(await request.body())
177+
if hasattr(request, "_json") and request._json is not None:
178+
token = request._json.get(self._token_key, "")
179+
elif hasattr(request, "_form") and request._form is not None:
180+
form_data: Union[None, UploadFile, str] = request._form.get(self._token_key)
181+
if not form_data or isinstance(form_data, UploadFile):
182+
raise MissingTokenError("Form data must be of type string")
183+
token = form_data
184+
else:
185+
token = self.get_csrf_from_body(await request.body())
178186
serializer = URLSafeTimedSerializer(secret_key, salt="fastapi-csrf-token")
179187
try:
180188
signature: str = serializer.loads(signed_token, max_age=time_limit)

0 commit comments

Comments
 (0)