Handling HTML form submissions safely is one of the most critical security aspects of web development. Naive form handling without validation exposes applications to SQL injection, malicious scripts, and Cross-Site Request Forgery (CSRF) attacks.
The Flask-WTF extension integrates WTForms with Flask, providing declarative form classes, field type casting, built-in input sanitization, and automatic CSRF token protection.
1. What is Cross-Site Request Forgery (CSRF)?
In a CSRF attack, an attacker tricks a victim's authenticated browser into executing unwanted actions on a trusted website:
Visual Architecture & Process Flow
How data and code flow step-by-step
Flowchart
Step 1
1. User logs into your bank or portal
Step 2
Session cookie stored in browser.
The Synchronizer Token Defense:
To prevent CSRF, Flask-WTF generates a cryptographically unique, unpredictable token bound to the user's active session. When submitting a form, the client must transmit this token. If the token is missing or mismatched, Flask immediately aborts the request with an HTTP 400 Bad Request (CSRF Token Missing or Invalid).
2. Installing and Configuring Flask-WTF
Install the extension:
1pip install flask-wtf
Flask-WTF requires a secret key configured on the application to cryptographically sign CSRF tokens:
1import os
2from flask import Flask
3from flask_wtf.csrf import CSRFProtect
4
5app = Flask(__name__)
6
7# Essential: Must be a strong, unpredictable random string
12 'X-CSRFToken': csrfToken // Verified automatically by CSRFProtect!
13 },
14 body: JSON.stringify({ comment: commentText })
15 });
16 return await response.json();
17}
18</script>
5. Exempting Webhooks with @csrf.exempt
External machine-to-machine services (such as Stripe payment webhooks or GitHub Actions webhooks) cannot provide a browser session CSRF token. Exempt specific endpoints using the @csrf.exempt decorator:
1@app.route("/webhooks/stripe", methods=["POST"])
2@csrf.exempt
3defstripe_webhook():
4# Verify signature using Stripe cryptographic headers instead of CSRF tokens
5return{"status":"Webhook received"},200
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
What application setting is mandatory for Flask-WTF to sign CSRF tokens?
Question 2
What HTTP status code does Flask-WTF return if a POST request fails CSRF verification?
Question 3
Which HTTP header does CSRFProtect inspect for AJAX / fetch requests?
Question 4
Why must payment gateway webhooks (e.g. Stripe, Razorpay) be marked with @csrf.exempt?
Question 5
How do you output the raw CSRF token value inside an HTML template?
Next Lesson
Form Classes & Built-In Field Validators
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.