← Back to all snippets
PYTHON

Implement Cross-Site Request Forgery (CSRF) Protection in Flask

Secure your Flask web application against CSRF attacks by integrating Flask-CSRFProtect to generate and validate CSRF tokens on forms, ensuring request authenticity.

from flask import Flask, render_template, request, session, redirect, url_for
from flask_wtf.csrf import CSRFProtect, generate_csrf

app = Flask(__name__)
app.config['SECRET_KEY'] = 'a_super_secret_key_that_should_be_long_and_random' # MUST be a strong, random key
CSRFProtect(app)

@app.route('/')
def index():
    # A simple form demonstrating CSRF token usage
    return f'''
    <h1>Welcome</h1>
    <p>This is a protected form.</p>
    <form method="POST" action="/update">
        <input type="hidden" name="csrf_token" value="{ generate_csrf() }">
        <label for="data">New Data:</label>
        <input type="text" id="data" name="data" required>
        <button type="submit">Submit</button>
    </form>
    '''

@app.route('/update', methods=['POST'])
def update_data():
    # Flask-CSRFProtect automatically validates the token on POST requests
    # if 'csrf_token' is in the form data or headers.
    new_data = request.form.get('data')
    if new_data:
        return f"Data updated successfully: {new_data}. CSRF token validated."
    return "No data provided.", 400

if __name__ == '__main__':
    app.run(debug=True)
How it works: This snippet demonstrates how to implement CSRF protection in a Flask application using `Flask-CSRFProtect`. It configures a secret key for token generation and then automatically injects and validates CSRF tokens for POST requests. The `generate_csrf()` function is used to manually include the token in a form, although `Flask-WTF` forms would handle this automatically. Upon form submission, `Flask-CSRFProtect` ensures the token is valid, preventing malicious cross-site requests.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs