Welcome to our comprehensive guide on Flask CSRF Protection! In this tutorial, we'll learn how to secure your Flask applications from Cross-Site Request Forgery (CSRF) attacks. 💡 Pro Tip: CSRF protection is crucial to ensure the integrity of your users' actions.
Before diving into Flask's CSRF protection, let's first understand what CSRF is. CSRF is a type of attack that tricks the user into submitting unintended commands on a web application they're currently authenticated with. 📝 Note: It exploits the trust a user has for a site and the authenticated session on that site.
Flask provides built-in support for CSRF protection. To use it, you'll need to make use of Flask-WTF extension and a CSRF protection form helper.
To install Flask-WTF, run the following command in your terminal:
pip install flask-wtfAfter installation, you need to configure Flask-WTF in your Flask app. Here's a sample configuration:
from flask import Flask
from flask_wtf import FlaskForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
wtf = FlaskForm(app)Now, let's create a simple form to demonstrate CSRF protection.
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, CSRFProtect
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')Add the CSRF token to your form's template:
<form method="POST" {{ form.csrf_token }}>
{{ form.name.label }}
{{ form.name }}
{{ form.submit }}
</form>When handling the form's submission, don't forget to include the CSRFProtect validator:
@app.route('/submit', methods=['POST'])
def submit():
form = MyForm()
if form.validate_on_submit():
print(f'Submitted name: {form.name.data}')
return 'Form submitted!'
return render_template('form.html', form=form)Let's create a simple Flask app with CSRF protection. Save the following code as app.py:
from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, CSRFProtect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
wtf = FlaskForm(app)
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), CSRFProtect()])
submit = SubmitField('Submit')
@app.route('/')
def index():
return render_template('index.html', form=MyForm())
@app.route('/submit', methods=['POST'])
def submit():
form = MyForm()
if form.validate_on_submit():
print(f'Submitted name: {form.name.data}')
return 'Form submitted!'
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)Create an index.html file in the same folder with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSRF Protection</title>
</head>
<body>
<h1>Submit your name 📝</h1>
<form method="POST">
{{ form.csrf_token }}
{{ form.name.label }}
{{ form.name }}
{{ form.submit }}
</form>
</body>
</html>Run the app with python app.py and visit http://127.0.0.1:5000/ in your browser. You'll see a simple form to submit your name. Try submitting the form multiple times and observe the console output.
What does CSRF stand for?
In this tutorial, we learned about CSRF attacks and how to protect Flask applications from them using the built-in CSRF protection provided by Flask-WTF. By now, you should have a good understanding of CSRF protection in Flask and how to implement it in your own projects. Happy coding! 🎯