CSRF protection is important in web applications. What does it mainly protect against?
Think about what kind of attack involves making a user unknowingly perform actions.
CSRF protection stops attackers from making users submit forms or requests without their consent, protecting user actions.
Consider a Flask app using Flask-WTF with CSRF protection enabled. What is the typical behavior when a form is submitted without a valid CSRF token?
Think about how Flask-WTF handles invalid CSRF tokens by default.
Flask-WTF raises a CSRFError exception and rejects the form submission if the CSRF token is missing or invalid.
Choose the correct code to enable CSRF protection in a Flask app using Flask-WTF.
from flask import Flask from flask_wtf.csrf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' # Add CSRF protection here
Remember that CSRFProtect can be initialized without app and then linked.
Option A correctly creates a CSRFProtect instance and initializes it with the Flask app using init_app. Option A works but is less flexible. Option A disables CSRF. Option A does not properly initialize CSRF.
Given this Flask-WTF form and template, the form submission raises a CSRF error. What is the likely cause?
class MyForm(FlaskForm): name = StringField('Name') submit = SubmitField('Submit') # Template snippet: # <form method="POST"> # {{ form.name.label }} {{ form.name() }} # {{ form.submit() }} # </form>
Check if the CSRF token field is included in the HTML form.
Flask-WTF requires the CSRF token field to be rendered inside the form. Without {{ form.csrf_token }}, the token is not sent, causing a CSRF error.
Consider this Flask route using Flask-WTF with CSRF protection enabled. What response does the user get if the form is submitted without a CSRF token?
from flask import Flask, render_template_string from flask_wtf import FlaskForm from flask_wtf.csrf import CSRFProtect from wtforms import StringField, SubmitField app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' csrf = CSRFProtect(app) class TestForm(FlaskForm): name = StringField('Name') submit = SubmitField('Send') @app.route('/', methods=['GET', 'POST']) def index(): form = TestForm() if form.validate_on_submit(): return 'Form submitted' return render_template_string(''' <form method="POST"> {{ form.csrf_token }} {{ form.name.label }} {{ form.name() }} {{ form.submit() }} </form> ''', form=form) # If a POST request is sent without CSRF token, what happens?
Think about how Flask-WTF handles missing CSRF tokens on POST requests.
Flask-WTF raises a 400 Bad Request error with a CSRF error message when the CSRF token is missing or invalid on POST requests.