CSRF protection stops bad websites from tricking you into doing things you don't want. It keeps your web forms safe.
0
0
CSRF protection in Flask
Introduction
When you have forms that change user data, like login or signup forms.
When users submit sensitive information, like passwords or payment details.
When your site allows actions like posting comments or making purchases.
When you want to keep your users safe from hidden attacks on your site.
Syntax
Flask
from flask_wtf import FlaskForm, CSRFProtect from flask import Flask app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' csrf = CSRFProtect(app) class MyForm(FlaskForm): pass # define your form fields here
You must set a SECRET_KEY in your Flask app for CSRF protection to work.
Use FlaskForm from flask_wtf to get CSRF tokens automatically in forms.
Examples
This form will have CSRF protection automatically included.
Flask
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField class CommentForm(FlaskForm): comment = StringField('Comment') submit = SubmitField('Post')
This enables CSRF protection for the whole Flask app.
Flask
from flask import Flask from flask_wtf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret123' csrf = CSRFProtect(app)
Sample Program
This Flask app shows a simple form with CSRF protection. The hidden CSRF token is included automatically. When you submit the form, it greets you by name.
Flask
from flask import Flask, render_template_string, request from flask_wtf import FlaskForm, CSRFProtect from wtforms import StringField, SubmitField app = Flask(__name__) app.config['SECRET_KEY'] = 'mysecretkey' csrf = CSRFProtect(app) class NameForm(FlaskForm): name = StringField('Your Name') submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): return f'Hello, {form.name.data}!' return render_template_string(''' <form method="POST"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name() }}<br> {{ form.submit() }} </form> ''', form=form) if __name__ == '__main__': app.run(debug=False)
OutputSuccess
Important Notes
Always use SECRET_KEY to keep CSRF tokens secure.
CSRF tokens are hidden fields in forms that change data.
Without CSRF protection, attackers can trick users into unwanted actions.
Summary
CSRF protection keeps your web forms safe from fake requests.
Use FlaskForm and CSRFProtect to add protection easily.
Always set a secret key in your Flask app for this to work.