SeaSurf is a Flask extension for preventing cross-site request forgery. CSRF vulnerabilities have been found in large and popular sites such as YouTube. These attacks are problematic because the mechanism they use is relatively easy to exploit. This extension attempts to aid you in securing your application from such attacks.

This extension is based on the excellent Django middleware.


Install the extension with one of the following commands:

$ easy_install flask-seasurf

or alternatively if you have pip installed:

$ pip install flask-seasurf


Using SeaSurf is fairly straightforward. Begin by importing the extension and then passing your application object back to the extension, like this:

from flaskext.seasurf import SeaSurf csrf = SeaSurf(app)


class flaskext.seasurf.SeaSurf(app=None)[source]

Primary class container for CSRF validation logic. The main function of this extension is to generate and validate CSRF tokens. The design and implementation of this extension is influenced by Django’s CSRF middleware.

Tokens are generated using a salted SHA1 hash. The salt is based off your application’s SECRET_KEY setting and a random range.

You might intialize SeaSurf something like this:

csrf = SeaSurf(app)

Validation will now be active for all requests whose methods are not GET, HEAD, OPTIONS, or TRACE.

When using other request methods, such as POST for instance, you will need to provide the CSRF token as a parameter. This can be achieved by making use of the Jinja global. In your template:

<form method="POST">
<input type="hidden" name="_csrf_token" value="{{ csrf_token }}">

This will assign a token to both the session cookie and the rendered HTML which will then be validated on the backend. POST requests missing this field will fail unless the header X-CSRFToken is specified.

Excluding Views From Validation

For views that use methods which may be validated but for which you wish to not run validation on you may make use of the exempt decorator to indicate that they should not be checked.

Parameters:app – The Flask application object, defaults to None.

A decorator that can be used to exclude a view from CSRF validation.

Example usage of exempt might look something like this:

csrf = SeaSurf(app)

def some_view():
    """This view is exempt from CSRF validation."""
    return render_template('some_view.html')
Parameters:view – The view to be wrapped by the decorator.

Initializes a Flask object app, binds CSRF validation to app.before_request, and assigns csrf_token as a Jinja global.

Parameters:app – The Flask application object.
Fork me on GitHub