minou
minou

Reputation: 16553

Flask form does not raise CSRFError for invalid token

The Flask-WTF docs state:

When CSRF validation fails, it will raise a CSRFError.

but I'm not getting the exception.

I'm using Flask-WTF for my forms like this:

class MyForm(FlaskForm):
    ...

In my handler I do this:

my_form = MyForm()
if my_form.validate_on_submit():
    ...

I expect the exception to be raised inside validate_on_submit but instead validate_on_submit just returns False.

Note that I am not doing this:

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

because my understanding is that is not needed if your forms depend from FlaskForm.

What am I doing wrong?

Upvotes: 1

Views: 219

Answers (1)

ekuusela
ekuusela

Reputation: 5282

Searching through the flask-wtf repo for CSRFError, it seems that the only time it is actually raised if you do use that

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

pattern you mentioned. It's only raised by _error_response in csrf.py which is called by the protect function. In contrast, for example the validate_csrf raises ValidationError when the token is invalid.

Upvotes: 1

Related Questions