CSRF Protection (Flask)

CSRF (Cross-Site Request Forgery) is an attack where a malicious site tricks a logged-in user's browser into submitting an unwanted request. Flask-WTF defends against it by embedding a secret token in each form that the server verifies.

Flask

Because browsers automatically send cookies (including session cookies) with any request, an attacker's page could POST to your app on the victim's behalf. The CSRF token breaks this: it is a per-session secret the attacker cannot know, so forged requests fail validation.

With Flask-WTF, protection is mostly automatic. Rendering {{ form.hidden_tag() }} (or {{ csrf_token() }}) places the token in the form, and validate_on_submit() rejects any POST whose token is missing or wrong, returning a 400 error.

For AJAX requests that do not use a form, you send the token in a header (commonly X-CSRFToken). CSRF protection requires a configured secret_key, since the token is signed with it.

Syntax

{{ form.hidden_tag() }}   <!-- in the template -->

Examples

Python

from flask_wtf.csrf import CSRFProtect

app.secret_key = "change-me"
csrf = CSRFProtect(app)
# Every POST form must now include {{ csrf_token() }}

Learn it in a lesson

See also

Back to the Dictionary