CSRF Protection in Flask

CSRF Protection in Flask

Cross-Site Request Forgery (CSRF) is a security vulnerability where an attacker can trick a user into unknowingly performing actions on a web application in which they're authenticated. Flask, a popular Python web framework, provides mechanisms to protect against CSRF attacks. One of the standard ways to implement CSRF protection in Flask is through the Flask-WTF extension, which integrates WTForms for form handling and includes CSRF protection.

Step 1: Install Flask-WTF

To get started, you need to install Flask-WTF. You can do this using pip:

pip install Flask-WTF 

Step 2: Configure Flask-WTF and CSRF Protection

In your Flask app, you need to configure Flask-WTF and specifically enable CSRF protection. You'll also need a secret key for your Flask app.

from flask import Flask from flask_wtf.csrf import CSRFProtect app = Flask(__name__) app.secret_key = 'your_secret_key' # Replace with a real secret key csrf = CSRFProtect(app) 

Replace 'your_secret_key' with a strong, random value.

Step 3: Include CSRF Token in Your Templates

When you create forms in your HTML templates, you need to include a hidden CSRF token field. Flask-WTF provides a convenient way to do this:

<form method="post"> {{ form.hidden_tag() }} <!-- your form fields here --> <input type="submit" value="Submit"> </form> 

The {{ form.hidden_tag() }} template code will include the CSRF token in your form. Ensure this is included in every form that performs state-changing operations (like POST requests).

Step 4: Validate CSRF Token on Form Submission

Flask-WTF automatically checks the CSRF token for you on form submissions. If the token is missing or incorrect, Flask-WTF raises a CSRFError.

Example: A Complete Flask App with CSRF Protection

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

from flask import Flask, render_template_string from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from flask_wtf.csrf import CSRFProtect app = Flask(__name__) app.secret_key = 'your_secret_key' csrf = CSRFProtect(app) class MyForm(FlaskForm): name = StringField('Name') submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): form = MyForm() if form.validate_on_submit(): # Handle valid form submission return f"Hello, {form.name.data}!" return render_template_string(''' <form method="post"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name() }} {{ form.submit() }} </form> ''', form=form) if __name__ == '__main__': app.run(debug=True) 

In this example, a form with a CSRF token is created. When the form is submitted, Flask-WTF checks the CSRF token automatically.

Notes

  • Always keep the secret key secure. It's used to sign session cookies and protect against CSRF attacks.
  • For AJAX requests, you'll need to send the CSRF token in the request headers. Flask-WTF provides a way to access the token.
  • Regularly update your Flask-WTF extension to ensure you have the latest security features and fixes.

Using Flask-WTF for CSRF protection is a robust and straightforward way to secure your Flask applications against CSRF attacks.


More Tags

serial-number point-of-sale pagedlist healthkit plpgsql getter standard-library application.properties webdriver apache-spark-1.3

More Programming Guides

Other Guides

More Programming Examples