Implementing CSRF Protection in Forms

Tutorial 3 of 5

Introduction

This tutorial aims to guide you through the process of implementing Cross-Site Request Forgery (CSRF) protection in your Flask forms. CSRF is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the website trusts. Therefore, it's crucial to protect your website and users from this type of attacks.

By the end of this tutorial, you will learn:

  • What CSRF attacks are and why they're dangerous
  • How to use Flask-WTF to protect your forms against CSRF attacks

The prerequisites for this tutorial are basic knowledge of Python and Flask, and a working Flask environment.

Step-by-Step Guide

To protect your Flask forms from CSRF attacks, you need to use the Flask-WTF extension. This extension provides you with simple ways to protect your forms. Here's how you can do it:

  1. Install Flask-WTF: You can install it via pip by running pip install flask-wtf

  2. Import the necessary modules: Import the FlaskForm class from flask_wtf and CSRFProtect from flask_wtf.csrf

  3. Initialize CSRF protection: After importing, you need to initialize CSRF protection for your app by creating an instance of CSRFProtect

  4. Use FlaskForm for your forms: When creating your forms, you should extend the FlaskForm class, which includes CSRF protection by default

Code Examples

Here's a basic example of a Flask app with CSRF protection:

from flask import Flask, render_template
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, SubmitField

app = Flask(__name__)
csrf = CSRFProtect(app)   # Initializing CSRF protection

class MyForm(FlaskForm):  # Form definition
    name = StringField('Name')
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def home():
    form = MyForm()
    if form.validate_on_submit():
        return 'Form Submitted!'
    return render_template('index.html', form=form)

In this code, we have a form with a single name field. The csrf = CSRFProtect(app) line initializes CSRF protection for our app. The MyForm class extends FlaskForm, which includes CSRF protection.

Summary

In this tutorial, you learned what CSRF attacks are and how they can affect your website. You also learned how to use Flask-WTF to add CSRF protection to your Flask forms.

Your next steps could be learning more about other types of web attacks and how to protect against them, or diving deeper into Flask-WTF and discovering its many other features.

Practice Exercises

  1. Create a Flask app with a form that includes CSRF protection. The form should have fields for username and password.

  2. Extend the app from the first exercise by adding a email field to the form.

Here's a possible solution for the first exercise:

from flask import Flask, render_template
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, PasswordField, SubmitField

app = Flask(__name__)
csrf = CSRFProtect(app)

class LoginForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    submit = SubmitField('Login')

@app.route('/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        return 'Login Successful!'
    return render_template('login.html', form=form)

In this solution, we created a LoginForm with username and password fields. We then used this form in our login view. The form is protected against CSRF attacks thanks to the csrf = CSRFProtect(app) line.