Skip to content

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”.

diagram the attack, and the one field that stops it mermaid
The browser attaches your cookies to any request aimed at your domain, including one triggered by a page the user did not know they were visiting. That is what makes the forged request look authentic. The token defeats it because the attacker can make the browser send a request, but cannot read your page to find out what the token is.

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

If you use FlaskForm and set SECRET_KEY, CSRF is enabled by default.

In your HTML form, add:

html
<form method="post">
  {{ form.hidden_tag() }}
  <!-- fields... -->
</form>

hidden_tag() includes the CSRF token.

You’ll typically see:

  • “The CSRF token is missing.”

This is a common beginner error.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading