CSRF Protection
CSRF stands for Cross-Site Request Forgery. It's a nasty attack where someone tricks your users into submitting forms to your site without their knowledge. Imagine a malicious link that automatically transfers money from your bank account - that's CSRF in action.
Every form that changes data (POST, PUT, DELETE) needs CSRF protection. The good news? Flask-WTF provides this automatically. You don't have to do much.
When you use Flask-WTF forms, CSRF protection is built in. The form.hidden_tag() method in your templates adds a special CSRF token field:
<form method="POST" action="">
{{ form.hidden_tag() }}
{# ... your form fields ... #}
</form>
That hidden_tag() generates a hidden input with a random token. When the form is submitted, Flask-WTF verifies this token matches the one in the user's session. If someone tries to submit a form from another site, the token won't match and the request is rejected.
You can configure the CSRF secret key in your Flask app. This is the key used to generate tokens:
app = Flask(__name__)
app.config['WTF_CSRF_SECRET_KEY'] = 'your-super-secret-key-here'
# Or use your existing SECRET_KEY:
app.config['SECRET_KEY'] = 'your-secret-key'
Flask-WTF automatically uses your SECRET_KEY if WTF_CSRF_SECRET_KEY isn't set. So make sure your SECRET_KEY is strong and kept secret.
If you need to disable CSRF for testing (development only!), you can do this:
app.config['WTF_CSRF_ENABLED'] = False # NEVER do this in production!
Or for a specific form, you can disable it when creating the form instance:
form = MyForm(csrf_enabled=False)
Remember: CSRF protection is essential for security. Never disable it in production. It's one of those things that seems like a hassle but protects your users from serious attacks.
Try it Yourself ->