Form validation fails due missing CSRF

The Flask-WTF CSRF infrastructure rejects a token if:

  • the token is missing. Not the case here, you can see the token in the form.

  • it is too old (default expiration is set to 3600 seconds, or an hour). Set the TIME_LIMIT attribute on forms to override this. Probably not the case here.

  • if no 'csrf_token' key is found in the current session. You can apparently see the session token, so that’s out too.

  • If the HMAC signature doesn’t match; the signature is based on the random value set in the session under the 'csrf_token' key, the server-side secret, and the expiry timestamp in the token.

Having eliminated the first three possibilities, you need to verify why the 4th step fails. You can debug the validation in flask_wtf/ file, in the validate_csrf() function.

For your setup, you need to verify that the session setup is correct (especially if you don’t use the default session configuration), and that you are using the correct server-side secret. The form itself could have a SECRET_KEY attribute set but is not stable across requests, or the app WTF_CSRF_SECRET_KEY key has changed (the latter defaults to the app.secret_key value).

The CSRF support was added in version 0.9.0, do check out the specific CSRF protection documentation if you upgraded. The standard Flask-WTF Form class includes the CSRF token as a hidden field, rendering the hidden fields is enough to include it:

{{ form.hidden_tag() }}

Leave a Comment