This Flask app shows a simple form with CSRF protection. The form includes a hidden CSRF token automatically. When you submit the form, it greets you by name.
Flask
from flask import Flask, render_template_string, request
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, SubmitField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret123'
csrf = CSRFProtect(app)
class NameForm(FlaskForm):
name = StringField('Name')
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
return f'Hello, {form.name.data}!'return render_template_string('''
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name() }}<br>
{{ form.submit() }}
</form>
''', form=form)
if __name__ == '__main__':
app.run(debug=False)
OutputSuccess
Important Notes
Always set a strong secret key to keep tokens secure.
CSRF tokens are unique per user session and help verify requests are genuine.
Flask-WTF makes adding CSRF protection easy with forms.
Summary
CSRF protection stops attackers from tricking users into unwanted actions.
Use Flask-WTF's CSRFProtect and include tokens in your forms.
Always protect POST routes that change data.
Practice
(1/5)
1. What is the main purpose of CSRF protection in a Flask web application?
easy
A. To speed up the loading time of web pages
B. To encrypt user passwords in the database
C. To prevent attackers from making users perform unwanted actions without their consent
D. To improve the visual design of forms
Solution
Step 1: Understand what CSRF stands for
CSRF means Cross-Site Request Forgery, which tricks users into submitting unwanted requests.
Step 2: Identify the purpose of CSRF protection
CSRF protection stops attackers from forcing users to perform actions they did not intend.
Final Answer:
To prevent attackers from making users perform unwanted actions without their consent -> Option C
Quick Check:
CSRF protection = prevent unwanted user actions [OK]
Hint: CSRF stops fake actions from attackers using your login [OK]
Common Mistakes:
Confusing CSRF with password encryption
Thinking CSRF improves page speed
Believing CSRF changes form appearance
2. Which of the following is the correct way to enable CSRF protection in a Flask app using Flask-WTF?
easy
A. from flask_wtf import CSRFProtect
app = Flask(__name__)
csrf = CSRFProtect(app)
csrf.init_app(app)
B. from flask_wtf import CSRFProtect
csrf = CSRFProtect()
app = Flask(__name__)
C. app = Flask(__name__)
app.csrf = True
D. from flask_wtf import CSRFProtect
csrf = CSRFProtect(app)
Solution
Step 1: Recall Flask-WTF CSRF setup
You import CSRFProtect and pass the Flask app instance to it to enable protection.
Step 2: Check the options for correct syntax
from flask_wtf import CSRFProtect
csrf = CSRFProtect(app) correctly imports CSRFProtect and initializes it with the app in one step.
Final Answer:
from flask_wtf import CSRFProtect
csrf = CSRFProtect(app) -> Option D
Quick Check:
CSRFProtect(app) initializes protection [OK]
Hint: Initialize CSRFProtect with app instance directly [OK]
Common Mistakes:
Calling CSRFProtect without passing app
Setting app.csrf = True (not valid)
Calling init_app after passing app (redundant)
3. Given this Flask route with CSRF protection enabled, what happens if the form is submitted without a CSRF token?