CSRF Protection in Flask
×


CSRF Protection in Flask

2205

Introduction

When developing web applications, security is a top priority. One common threat developers face is Cross-Site Request Forgery (CSRF). In this post, we’ll explore how to implement CSRF protection in Flask to defend your app against these attacks using the Flask-WTF extension.

What is CSRF?

CSRF, or Cross-Site Request Forgery, is a type of attack where unauthorized commands are transmitted from a user that the web application trusts. It tricks users into submitting malicious requests without their consent, which could result in data manipulation or unwanted actions.

How CSRF Works

In a CSRF attack, the attacker tricks a user into making a request to a site where the user is already authenticated. Since the browser automatically includes the session cookies, the request appears legitimate. This can lead to serious consequences like data deletion or unauthorized actions.

Installing Flask-WTF

To prevent CSRF attacks, we can use Flask-WTF, which extends Flask with form handling capabilities and built-in CSRF protection.

pip install flask-wtf

Setting Up Flask-WTF

First, configure your application with a secret key which is used to generate secure tokens.

from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)
app.secret_key = 'your-secret-key'

Creating a CSRF-Protected Form

Flask-WTF automatically adds CSRF protection to forms. Here’s an example of a simple form with a name field and a submit button:

class NameForm(FlaskForm):
    name = StringField('Enter your name', validators=[DataRequired()])
    submit = SubmitField('Submit')

Using the Form in a Route

Let’s integrate the form with a route and render it using a template.

from flask import render_template

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        return f"Hello, {form.name.data}!"
    return render_template('form.html', form=form)

HTML Template with CSRF Token

The form.hidden_tag() method is essential — it inserts the CSRF token as a hidden input. Without it, form validation will fail.

<form method="POST">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name() }}
    {{ form.submit() }}
</form>

Handling CSRF Errors

If the CSRF token is missing or incorrect, Flask-WTF raises a CSRFError. You can handle this error gracefully using Flask’s error handler.

from flask_wtf.csrf import CSRFError

@app.errorhandler(CSRFError)
def handle_csrf_error(e):
    return 'CSRF token missing or incorrect.', 400

Summary

CSRF protection in Flask is crucial to securing your web forms from unauthorized actions. With the help of Flask-WTF, CSRF tokens are automatically handled, making your forms safer and easier to manage. Always remember to configure a strong secret key and include the hidden token in every form.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat