📖 Scenario: You are building a simple Flask web app with a form where users can submit their email to subscribe to a newsletter. To keep the app safe from Cross-Site Request Forgery (CSRF) attacks, you need to add CSRF protection.
🎯 Goal: Build a Flask app with a subscription form that includes CSRF protection using Flask-WTF.
📋 What You'll Learn
Create a Flask app with Flask-WTF extension
Define a subscription form with CSRF protection
Render the form in a template with CSRF token
Handle form submission securely with CSRF validation
💡 Why This Matters
🌍 Real World
CSRF protection is essential for any web app that accepts form submissions to prevent attackers from tricking users into submitting unwanted requests.
💼 Career
Understanding and implementing CSRF protection is a key skill for web developers to build secure applications and protect user data.
Progress0 / 4 steps
1
Set up Flask app and subscription form
Create a Flask app instance called app and define a subscription form class called SubscribeForm that inherits from FlaskForm. The form should have a single field called email of type EmailField and a submit button called submit.
Flask
Hint
Remember to import Flask, FlaskForm, EmailField, and SubmitField. Then create app and define the form class with the exact field names.
2
Configure secret key for CSRF protection
Add a secret key configuration to the app by setting app.config['SECRET_KEY'] to the string 'mysecretkey'. This key is required for CSRF protection to work.
Flask
Hint
Set the secret key on the app.config dictionary exactly as shown.
3
Create a route to display and process the form
Define a route /subscribe with a function called subscribe. Inside it, create an instance of SubscribeForm called form. Use form.validate_on_submit() to check if the form was submitted and is valid. If valid, return the string 'Subscription successful'. Otherwise, render a template called subscribe.html passing the form.
Flask
Hint
Remember to import render_template and set the route methods to ['GET', 'POST']. Use the exact function and variable names.
4
Create the HTML template with CSRF token
Write the HTML code for subscribe.html that contains a form which posts to /subscribe. Inside the form, include the CSRF token by adding {{ form.csrf_token }}. Also include the email input field with {{ form.email.label }} and {{ form.email() }}, and the submit button with {{ form.submit() }}.
Flask
Hint
Make sure to include the CSRF token inside the form to enable CSRF protection.
Practice
(1/5)
1. What is the main purpose of CSRF protection in a Flask web application?
easy
A. To prevent unauthorized commands from being transmitted from a user the website trusts
B. To speed up the loading time of web pages
C. To encrypt user passwords in the database
D. To improve the visual design of forms
Solution
Step 1: Understand CSRF meaning
CSRF stands for Cross-Site Request Forgery, which tricks users into submitting unwanted actions.
Step 2: Identify CSRF protection goal
Protection stops fake requests that appear to come from trusted users, preventing unauthorized actions.
Final Answer:
To prevent unauthorized commands from being transmitted from a user the website trusts -> Option A
Secret key set + CSRFProtect(app) = correct setup [OK]
Hint: Set secret_key before CSRFProtect(app) call [OK]
Common Mistakes:
Not setting secret_key or setting it after CSRFProtect
Passing no app to CSRFProtect
Setting secret_key to None disables protection
3. Given this Flask form code snippet, what happens if the CSRF token is missing or invalid when submitting the form?
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
class MyForm(FlaskForm):
name = StringField('Name')
submit = SubmitField('Send')
medium
A. The form submission is accepted without any error
B. The form automatically regenerates a new CSRF token and retries
C. A CSRFError is raised and the request is rejected
D. The form data is saved but a warning is logged
Solution
Step 1: Understand FlaskForm CSRF behavior
FlaskForm automatically checks for a valid CSRF token on submission.
Step 2: Effect of missing/invalid token
If the token is missing or wrong, Flask-WTF raises a CSRFError and rejects the request.
Final Answer:
A CSRFError is raised and the request is rejected -> Option C
Quick Check:
Invalid CSRF token = CSRFError raised [OK]
Hint: Missing CSRF token causes error and blocks form [OK]
Common Mistakes:
Assuming form submits anyway without token
Thinking token regenerates automatically on failure
Believing data saves with just a warning
4. You added CSRFProtect to your Flask app but still get CSRF errors on form submission. Which of these is the most likely cause?
medium
A. You called csrf = CSRFProtect(app) before creating the Flask app
B. You set app.secret_key to a strong random value
C. You used FlaskForm instead of plain WTForms Form
D. You forgot to include {{ form.csrf_token }} inside your HTML form
Solution
Step 1: Check CSRF token inclusion in form
The CSRF token must be included in the HTML form using {{ form.csrf_token }} for validation.
Step 2: Understand error cause
If the token is missing in the form, the server rejects the submission with a CSRF error.
Final Answer:
You forgot to include {{ form.csrf_token }} inside your HTML form -> Option D
Quick Check:
Missing token in form = CSRF errors [OK]
Hint: Always add {{ form.csrf_token }} inside your form tag [OK]
Common Mistakes:
Assuming secret_key causes errors when set correctly
Thinking FlaskForm causes errors instead of helping
Initializing CSRFProtect before app creation causes syntax error, not CSRF error
5. You want to protect an API endpoint in Flask that accepts JSON POST requests from your frontend. Which approach correctly applies CSRF protection?
hard
A. Disable CSRF protection for JSON endpoints because tokens only work with HTML forms
B. Use CSRFProtect and require the frontend to send the CSRF token in a custom header, then validate it in Flask
C. Add {{ form.csrf_token }} in the JSON payload sent by the frontend
D. Use FlaskForm on the API endpoint without any token validation
Solution
Step 1: Understand CSRF with JSON APIs
CSRF tokens can protect JSON POST requests if the token is sent in headers and validated server-side.
Step 2: Correct method to protect API
Use CSRFProtect and require frontend to send token in a custom header (e.g., X-CSRFToken), then validate it in Flask.
Final Answer:
Use CSRFProtect and require the frontend to send the CSRF token in a custom header, then validate it in Flask -> Option B
Quick Check:
CSRF token in header + validation = secure JSON API [OK]
Hint: Send CSRF token in header for JSON API protection [OK]
Common Mistakes:
Thinking CSRF tokens only work with HTML forms
Putting CSRF token inside JSON body without validation
Using FlaskForm without token validation on APIs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.