wtforms / flask-wtf

Simple integration of Flask and WTForms, including CSRF, file upload and Recaptcha integration.
https://flask-wtf.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.46k stars 310 forks source link

CSRF Token does not attach to session #494

Open Arthurdb1999 opened 2 years ago

Arthurdb1999 commented 2 years ago

I'm using Flask as an API and ReactJS for my front-end, and followed the CSRF Protection Docs with Javascript Requests (Axios).

Please follow my Init App file to see my code: https://gist.github.com/Arthurdb1999/c72226800f19d6c8553d216fb1720900

When making a request, the following Exception is logged:

Traceback:

  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask_wtf\csrf.py", line 261, in protect
    validate_csrf(self._get_csrf_token())
  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask_wtf\csrf.py", line 103, in validate_csrf
    raise ValidationError("The CSRF session token is missing.")
wtforms.validators.ValidationError: The CSRF session token is missing.    

During handling of the above exception, another exception occurred:       

Traceback (most recent call last):
  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask\app.py", line 1497, in full_dispatch_request
    rv = self.preprocess_request()
  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask\app.py", line 1838, in preprocess_request
    rv = self.ensure_sync(func)()
  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask_wtf\csrf.py", line 229, in csrf_protect
    self.protect()
  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask_wtf\csrf.py", line 264, in protect
    self._error_response(e.args[0])
  File "C:\Users\arthur\Documents\Arthur\MyApp\venv\Lib\site-packages\flask_wtf\csrf.py", line 307, in _error_response
    raise CSRFError(reason)
flask_wtf.csrf.CSRFError: 400 Bad Request: The CSRF session token is missing.

So I started to debug the error at csrf.py file in the flask-wtf folder of my virtual environment and found out that the generate_csrf() function is never called, and that's why I'm posting this as a bug report. Because of that, I think the token will never attach to session.

I'm sending the following header to the API: X-CSRFToken: {{ csrf_token() }}, and also tried to put the whole token on it (which wouldn't be secure).

Am I doing something wrong or is this really a bug to be fixed? I can give any other environment info if needed.

Environment:

eljeffeg commented 2 years ago

I think this might describe what I'm seeing https://github.com/wtforms/flask-wtf/issues/424. Sometimes the session has an empty csrf_token.

michaels-atbay commented 1 year ago

Happens to me as well. Any news on this?