Flask-WTF Setup & CSRF Token Protection
Flask-WTF Setup & CSRF Token Protection
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
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:
Flask-WTF requires a secret key configured on the application to cryptographically sign CSRF tokens:
3. Rendering CSRF Tokens in HTML Forms
When rendering raw HTML forms without WTForms form classes, inject the CSRF token using csrf_token():
4. Protecting AJAX and Fetch API Requests
For Single Page Apps or JavaScript fetch() requests, pass the CSRF token via the X-CSRFToken HTTP header:
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:
Practice Quiz
CSRFProtect inspect for AJAX / fetch requests?@csrf.exempt?Form Classes & Built-In Field Validators
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Jinja2 Macros & Reusable UI Components | Form Classes & Built-In Field Validators |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.