garter / docs / content / csrf.markdown

Full commit

<h1><a href="">CSRF Protection</a></h1>

The internet is a dangerous place. One common type of attack your site's users can fall victim to is Cross-site Request Forgery attacks.

Garter provides a simple way to guard against these attacks, based on this snippet from the Flask snippet site.

To activate CSRF protection for your Flask application you need to do two things. First, call Garter's csrf function with your Flask app as a parameter:

from garter.csrf import csrf

Once you do that you'll need to add a CSRF token to every form on your site that makes an HTTP POST request:

<input type="hidden" value="{{ csrf_token() }}">

If you have certain views that need to be excluded from this protection (perhaps they receive POST requests from a third-party site) you can use the csrf_exempt decorator to disable protection:

from garter.csrf import csrf, csrf_exempt

def my_receiving_view():
    # ...


If for some reason you want to know when a CSRF attack happens, you can pass a function to the csrf call and it will be called whenever Garter detects an attack:

from garter.csrf import csrf

attacks = 0
def count_csrf_attacks(endpoint, arguments):
    attacks += 1

csrf(app, on_csrf=count_csrf_attacks)

This function must take two parameters:

  • endpoint - A string representing the view that would normally handle this request.
  • arguments - The arguments that would normally be passed (if any) to that view.

You can use this function to do anything you like; counting attacks is just a simple example.