Here is a little snippet for CSRF protection in a Bottle.py web-application which can be used as a Bottle.py app-plugin.

This was mostly inspired by a question on Stackoverflow.com but i disliked the decorator-type and created this plugin-type CSRF validator instead.

This plugin will generate a new CSRF token (generator implementation not provided here) for each request and save it to session. You can then pass the session object to your template and simply add a hidden input field to all form elements in your templates, which should have the value of CSRF token in session object. I have set up my app so that the session object is passed to the templates by default. And when a form is POSTed, this plugin will validate if the post data contains a CSRF token and if the provided token matches the one stored in session object earlier. You can easily extend it to check PUT/DELETE requests too.

Some feature ideas:


  • make this work with Ajax requests too

    • refactor the plugin to check request headers too (and not just post data)

    • add some Javascript code to base template to intercept all Ajax requests and add the CSRF token as a request header; like this:


  • avoid manually adding hidden input elements to form elements

    • i still haven't got this to work properly but the idea is: on body-load event, bind to all form elements' submit events and append the CSRF token to the form-data Javascript