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”.
sequenceDiagram
participant U as User's browser
participant E as evil-site.com
participant A as your-app.com
Note over U,A: the user is already logged in to your-app.com
U->>E: visits a page on the attacker's site
E-->>U: a hidden form that auto-submits to your-app.com
U->>A: POST /transfer (cookies attached automatically)
alt no CSRF token checked
A-->>U: request accepted -- the attack worked
else CSRF token required
A->>A: is there a token, and does it match the session?
A-->>U: 400 Bad Request -- the attacker could not supply one
end
How Flask-WTF protects you
Section titled “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
Section titled “Enabling CSRF”If you use FlaskForm and set SECRET_KEY, CSRF is enabled by default.
Include the hidden token in templates
Section titled “Include the hidden token in templates”In your HTML form, add:
<form method="post">
{{ form.hidden_tag() }}
<!-- fields... -->
</form>hidden_tag() includes the CSRF token.
If you forget hidden_tag()
Section titled “If you forget hidden_tag()”You’ll typically see:
- “The CSRF token is missing.”
This is a common beginner error.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading