CSRF Token does not attach to session
Opened this issue · 2 comments
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:
- Python version: 3.9.0
- Flask-WTF version: 0.15.1 or 1.0.0 (error raises on both)
- Flask version: 2.0.0
I think this might describe what I'm seeing #424. Sometimes the session has an empty csrf_token.
Happens to me as well. Any news on this?