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.
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
CsrfMiddleware does two things:
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'.
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.
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:
MIDDLEWARE_CLASSES = ( "django.middleware.gzip.GZipMiddleware", "lukeplant_me_uk.django.middleware.csrf.CsrfMiddleware", "django.middleware.sessions.SessionMiddleware", )
MIT (which means in short that it is open source and free of charge for any use)
© 2005 Luke Plant <L dot Plant dot 98 at
cantab dot net>
Back to lukeplant.me.uk