.. _ref-contrib-csrf: ===================================== Cross Site Request Forgery protection ===================================== .. module:: django.middleware.csrf :synopsis: Protects against Cross Site Request Forgeries The CSRF middleware and template tag provides easy-to-use protection against `Cross Site Request Forgeries`_. This type of attack occurs when a malicious Web site contains a link, a form button or some javascript that is intended to perform some action on your Web site, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, 'login CSRF', where an attacking site tricks a user's browser into logging into a site with someone else's credentials, is also covered. The first defense against CSRF attacks is to ensure that GET requests are side-effect free. POST requests can then be protected by following the steps below. .. versionadded:: 1.2 The 'contrib' apps, including the admin, use the functionality described here. Because it is security related, a few things have been added to core functionality to allow this to happen without any required upgrade steps. .. _Cross Site Request Forgeries: http://www.squarefree.com/securitytips/web-developers.html#CSRF How to use it ============= .. versionchanged:: 1.2 The template tag functionality (the recommended way to use this) was added in version 1.2. The previous method (still available) is described under `Legacy method`_. To enable CSRF protection for your views, follow these steps: 1. Add the middleware ``'django.middleware.csrf.CsrfViewMiddleware'`` to your list of middleware classes, :setting:`MIDDLEWARE_CLASSES`. (It should come before ``CsrfResponseMiddleware`` if that is being used, and before any view middleware that assume that CSRF attacks have been dealt with.) Alternatively, you can use the decorator ``django.views.decorators.csrf.csrf_protect`` on particular views you want to protect. This is **not recommended** by itself, since if you forget to use it, you will have a security hole. The 'belt and braces' strategy of using both is fine, and will incur minimal overhead. 2. In any template that uses a POST form, use the ``csrf_token`` tag inside the ``