CsrfMiddleware - simple Cross Site Request Forgery protection

PLEASE NOTE

CsrfMiddleware is now available in 'contrib' in current Django development version. See the CSRF documentation. If you are using an older version of Django, this page might still be useful.

Summary

CsrfMiddleware is a very easy to use middleware module for the Django web framework that provides protection against Cross Site Request Forgeries.

It really does work perfectly, plug-in and done :-). Even Ajax-Stuff didn't make any problems (the only thing I had to think of was to set the form method _in_ the form and not to rely on setting the XMLHttpRequest query method). Thanks!
Andreas Stuhlmüller

How it works

CsrfMiddleware does two things:

  1. it modifies outgoing requests by adding a hidden form field to all 'POST' forms, with name 'csrfmiddlewaretoken' and a value which is a hash of the session ID plus a secret. If there is no session ID set, this modification of the response isn't done, so there is very little performance penalty for those requests that don't have a session.
  2. on all incoming POST requests that have the session cookie set, it checks that the 'csrfmiddlewaretoken' is present and correct. If it isn't, you get a 403 error

CsrfMiddleware requires Django's session framework to work. If you have a custom authentication system that manually sets cookies and the like, it won't help you.

It deliberately only targets HTTP POST requests (and the corresponding POST forms). GET requests ought never to have side effects (if you are using HTTP GET and POST correctly), and so a CSRF attack with a GET request will always be harmless.

It also checks the Content-Type before modifying the response, and only modifies 'text/html' and 'application/xml+xhtml'.

Limitations

If your app creates HTML pages and forms in some unusual way, (e.g. it sends fragments of HTML in javascript document.write statements) you might bypass the filter that adds the hidden field to the form, in which case form submission will always fail. You will need to think carefully about the 'How it works' section. If you need a public method added to the module to work around this (e.g. to get the csrf token manually), let me know what you need.

Download

Installation and usage

Extract the package and place it somewhere in your python path, as with all middleware classes. You then need to add two lines to your Django settings file:

LICENSE

MIT (which means in short that it is open source and free of charge for any use)

TODO

Changelog

Version 1.1 - 2005-12-14

Version 1.0 - 2005-11-19

2005-11-04

About

© 2005 Luke Plant <L dot Plant dot 98 at cantab dot net>
Back to lukeplant.me.uk