1
votes

I am trying to add CSRF token protection using Flask-WTF's CSRFProtect extension. The app isn't using WTForms except for this CSRF protection.

I followed the docs but I get "400 Bad Request The CSRF token is missing".

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)

I put the following in the templates (with form or without a form) but I get the same error.

<form method="post">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
</form>
1

1 Answers

2
votes

As described in this answer, inspect the actual CSFR validation flow:

You can debug the validation in flask_wtf/csrf.py file, in the validate_csrf() function.

For me, the issue was caused by a recent update of Flask and Flask-WTF. I solved it by removing all the .pyc files in the project. However, I don't know the actual root cause in my case.

find . -name '*.pyc' -delete

 

Later edit:

  • update to latest versions of Flask, Flask-WTF;
  • on your development environment, if using HTTP instead of HTTPS, make sure SESSION_COOKIE_SECURE is not set to True. See this.