Preventing CSRF attacks
CSRF is an attack whereby authenticated users are duped into diverting sensitive data to hidden and malicious sites. This attack happens when users perform POST
, DELETE
, PUT
, or PATCH
transactions, whereby form data are retrieved and submitted to the application. In Flask, the most common solution is to use Flask-WTF
because it has a built-in CSRFProtect
class that globally protects every form transaction of the application. Once enabled, CSRFProtect
allows the generation of unique tokens for every form transaction. Those form submissions that will not generate a token will cause CSRFProtect
to trigger an error message, detecting a CSRF attack.
Chapter 4 highlights the setup of the Flask-WTF
module in a Flask application. After its installation, import CSRFProtect
and instantiate it in create_app()
, as shown in the following code snippet:
from flask_wtf.csrf import CSRFProtect def create_app(config_file): app = Flask(__name__,template_folder...