CSRF Protection
CSRF (Cross-Site Request Forgery) is a common web attack.
It happens when:
- a user is logged in to your site
- a malicious site tricks their browser into sending a POST request to your site
- the browser includes your user’s cookies automatically
If you don’t validate a CSRF token, the request may look “legitimate”.
How Flask-WTF protects you
Flask-WTF adds a hidden token field to your form.
On submit, it verifies:
- the token matches the user session
- the request is coming from your site
Enabling CSRF
If you use FlaskFormFlaskForm and set SECRET_KEYSECRET_KEY, CSRF is enabled by default.
Include the hidden token in templates
In your HTML form, add:
<form method="post">
{{ form.hidden_tag() }}
<!-- fields... -->
</form><form method="post">
{{ form.hidden_tag() }}
<!-- fields... -->
</form>hidden_tag()hidden_tag() includes the CSRF token.
If you forget hidden_tag()
You’ll typically see:
- “The CSRF token is missing.”
This is a common beginner error.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
