CSRF protection stops bad websites from tricking you into doing things you don't want. It keeps your web app safe from sneaky attacks.
0
0
CSRF protection concept in Flask
Introduction
When you have forms that change data, like login or signup forms.
When users can update their profile or settings on your site.
When your app processes payments or sensitive actions.
When you want to keep user sessions secure from outside attacks.
Syntax
Flask
from flask import Flask from flask_wtf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' csrf = CSRFProtect(app)
You need to set a secret key for security.
CSRFProtect wraps your app to add protection automatically.
Examples
Basic setup to enable CSRF protection in a Flask app.
Flask
from flask import Flask from flask_wtf import CSRFProtect app = Flask(__name__) app.config['SECRET_KEY'] = 'secret123' csrf = CSRFProtect(app)
Example of a POST route that will be protected by CSRF automatically.
Flask
@app.route('/submit', methods=['POST']) def submit(): # Your form handling code here return 'Form submitted!'
In your HTML form, include
form.hidden_tag() to add the CSRF token.Flask
<form method="POST" action="/submit"> {{ form.hidden_tag() }} <input type="text" name="name"> <input type="submit" value="Send"> </form>
Sample Program
This Flask app shows a simple form with CSRF protection. The form includes a hidden CSRF token 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'] = 'secret123' csrf = CSRFProtect(app) class NameForm(FlaskForm): name = StringField('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 set a strong secret key to keep tokens secure.
CSRF tokens are unique per user session and help verify requests are genuine.
Flask-WTF makes adding CSRF protection easy with forms.
Summary
CSRF protection stops attackers from tricking users into unwanted actions.
Use Flask-WTF's CSRFProtect and include tokens in your forms.
Always protect POST routes that change data.