CSRF protection is important in web applications. What does it mainly prevent?
Think about what happens if a malicious site tricks a logged-in user into submitting a form.
CSRF protection stops unauthorized commands sent from a userβs browser without their knowledge, protecting user actions.
Consider a Flask app using Flask-WTF with CSRF enabled. What is the typical behavior when a form is submitted without the correct CSRF token?
CSRF protection is designed to block suspicious requests.
Flask-WTF raises a CSRFError when the token is missing or invalid, stopping the form processing.
Choose the code that properly sets up CSRF protection in a Flask app using Flask-WTF.
from flask import Flask from flask_wtf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' # Which line correctly enables CSRF protection?
Check how the CSRFProtect object is created and linked to the app.
Both creating CSRFProtect with the app as an argument or creating it first and then calling init_app(app) are valid patterns.
Given this Flask form code, why might a CSRF error occur?
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField class MyForm(FlaskForm): name = StringField('Name') submit = SubmitField('Send') # In the template: # <form method="POST"> # {{ form.name.label }} {{ form.name() }} # {{ form.submit() }} # </form>
CSRF token must be included in the form HTML.
Flask-WTF requires the CSRF token field to be rendered inside the form for validation.
Consider this Flask route using Flask-WTF CSRF protection. What response will the client receive if the POST request lacks a CSRF token?
from flask import Flask, request from flask_wtf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' csrf = CSRFProtect() csrf.init_app(app) @app.route('/submit', methods=['POST']) def submit(): return 'Form submitted successfully' # Client sends POST to /submit without CSRF token.
CSRFProtect blocks requests missing valid tokens with a specific error code.
Flask-WTF returns HTTP 400 Bad Request with a CSRF error when token is missing or invalid.