0
0
Flaskframework~30 mins

CSRF protection in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
CSRF Protection in Flask Forms
📖 Scenario: You are building a simple Flask web app with a form where users can submit their email to subscribe to a newsletter. To keep the app safe from Cross-Site Request Forgery (CSRF) attacks, you need to add CSRF protection.
🎯 Goal: Build a Flask app with a subscription form that includes CSRF protection using Flask-WTF.
📋 What You'll Learn
Create a Flask app with Flask-WTF extension
Define a subscription form with CSRF protection
Render the form in a template with CSRF token
Handle form submission securely with CSRF validation
💡 Why This Matters
🌍 Real World
CSRF protection is essential for any web app that accepts form submissions to prevent attackers from tricking users into submitting unwanted requests.
💼 Career
Understanding and implementing CSRF protection is a key skill for web developers to build secure applications and protect user data.
Progress0 / 4 steps
1
Set up Flask app and subscription form
Create a Flask app instance called app and define a subscription form class called SubscribeForm that inherits from FlaskForm. The form should have a single field called email of type EmailField and a submit button called submit.
Flask
Need a hint?

Remember to import Flask, FlaskForm, EmailField, and SubmitField. Then create app and define the form class with the exact field names.

2
Configure secret key for CSRF protection
Add a secret key configuration to the app by setting app.config['SECRET_KEY'] to the string 'mysecretkey'. This key is required for CSRF protection to work.
Flask
Need a hint?

Set the secret key on the app.config dictionary exactly as shown.

3
Create a route to display and process the form
Define a route /subscribe with a function called subscribe. Inside it, create an instance of SubscribeForm called form. Use form.validate_on_submit() to check if the form was submitted and is valid. If valid, return the string 'Subscription successful'. Otherwise, render a template called subscribe.html passing the form.
Flask
Need a hint?

Remember to import render_template and set the route methods to ['GET', 'POST']. Use the exact function and variable names.

4
Create the HTML template with CSRF token
Write the HTML code for subscribe.html that contains a form which posts to /subscribe. Inside the form, include the CSRF token by adding {{ form.csrf_token }}. Also include the email input field with {{ form.email.label }} and {{ form.email() }}, and the submit button with {{ form.submit() }}.
Flask
Need a hint?

Make sure to include the CSRF token inside the form to enable CSRF protection.