Flask-SeaSurf

raw JSON →
2.0.0 verified Fri May 01 auth: no python

Flask-SeaSurf is an updated CSRF protection extension for Flask applications. It provides cross-site request forgery prevention via tokens, with support for AJAX requests, cookie-based tokens, and exclusion patterns. Version 2.0.0 is the latest release, with maintenance as needed.

pip install flask-seasurf
error ImportError: cannot import name 'SeaSurf' from 'flask.ext.seasurf'
cause Using the deprecated flask.ext.seasurf namespace, removed in Flask 2.0.
fix
Change import to 'from flask_seasurf import SeaSurf'.
error RuntimeError: A secret key is required to use CSRF.
cause Flask app does not have SECRET_KEY configured.
fix
Add 'app.secret_key = "your-secret-key"' before initializing SeaSurf.
breaking In version 2.0.0, the CSRF token is no longer automatically injected into responses. You must manually include {{ csrf_token() }} in your templates or use the `add_csrf_token` decorator.
fix Update templates to render csrf_token() or decorate routes with @csrf.add_csrf_token.
breaking Flask-SeaSurf 2.0.0 changed the default token cookie name from 'csrf_token' to '_csrf_token' to avoid conflicts with other frameworks.
fix Update any client-side code that reads the cookie, or configure the cookie name via CSRF_COOKIE_NAME.
gotcha SeaSurf requires `SECRET_KEY` to be set on the app, otherwise it raises a RuntimeError on initialization.
fix Set app.secret_key or SECRET_KEY config before initializing SeaSurf.
gotcha When using AJAX, the token must be sent via the X-CSRFToken header (or configured header). SeaSurf does not check POST body tokens by default for AJAX requests.
fix Include the token in a header like X-CSRFToken with the same value as the cookie or template token.

Initialize SeaSurf with the Flask app and include {{ csrf_token() }} in forms.

from flask import Flask
from flask_seasurf import SeaSurf

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

csrf = SeaSurf(app)

@app.route('/')
def index():
    return '''<form action="/submit" method="post">
        <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
        <input type="submit">
    </form>'''

@app.route('/submit', methods=['POST'])
def submit():
    return 'OK'

if __name__ == '__main__':
    app.run()