Cross Site Request Forgery protection

The CSRF middleware and template tag provides easy-to-use protection againstCross Site Request Forgeries. This type of attack occurs when a maliciouswebsite contains a link, a form button or some JavaScript that is intended toperform some action on your website, using the credentials of a logged-in userwho 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 intoa site with someone else's credentials, is also covered.

The first defense against CSRF attacks is to ensure that GET requests (and other'safe' methods, as defined by RFC 7231#section-4.2.1) are side effect free.Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then beprotected by following the steps below.

How to use it

To take advantage of CSRF protection in your views, follow these steps:

  • The CSRF middleware is activated by default in the MIDDLEWAREsetting. If you override that setting, remember that'django.middleware.csrf.CsrfViewMiddleware' should come before any viewmiddleware that assume that CSRF attacks have been dealt with.

If you disabled it, which is not recommended, you can usecsrf_protect() on particular viewsyou want to protect (see below).

  • In any template that uses a POST form, use the csrf_token tag insidethe <form> element if the form is for an internal URL, e.g.:
  1. <form method="post">{% csrf_token %}

This should not be done for POST forms that target external URLs, sincethat would cause the CSRF token to be leaked, leading to a vulnerability.

  • In the corresponding view functions, ensure thatRequestContext is used to render the response sothat {% csrf_token %} will work properly. If you're using therender() function, generic views, or contrib apps,you are covered already since these all use RequestContext.

AJAX

While the above method can be used for AJAX POST requests, it has someinconveniences: you have to remember to pass the CSRF token in as POST data withevery POST request. For this reason, there is an alternative method: on eachXMLHttpRequest, set a custom X-CSRFToken header (as specified by theCSRF_HEADER_NAME setting) to the value of the CSRF token. This isoften easier because many JavaScript frameworks provide hooks that allowheaders to be set on every request.

First, you must get the CSRF token. How to do that depends on whether or notthe CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY settingsare enabled.

The recommended source for the token is the csrftoken cookie, which will beset if you've enabled CSRF protection for your views as outlined above.

The CSRF token cookie is named csrftoken by default, but you can controlthe cookie name via the CSRF_COOKIE_NAME setting.

Acquiring the token is straightforward:

  1. function getCookie(name) {
  2. var cookieValue = null;
  3. if (document.cookie && document.cookie !== '') {
  4. var cookies = document.cookie.split(';');
  5. for (var i = 0; i < cookies.length; i++) {
  6. var cookie = cookies[i].trim();
  7. // Does this cookie string begin with the name we want?
  8. if (cookie.substring(0, name.length + 1) === (name + '=')) {
  9. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  10. break;
  11. }
  12. }
  13. }
  14. return cookieValue;
  15. }
  16. var csrftoken = getCookie('csrftoken');

The above code could be simplified by using the JavaScript Cookie library to replace getCookie:

  1. var csrftoken = Cookies.get('csrftoken');

注解

The CSRF token is also present in the DOM, but only if explicitly includedusing csrf_token in a template. The cookie contains the canonicaltoken; the CsrfViewMiddleware will prefer the cookie to the token inthe DOM. Regardless, you're guaranteed to have the cookie if the token ispresent in the DOM, so you should use the cookie!

警告

If your view is not rendering a template containing the csrf_tokentemplate tag, Django might not set the CSRF token cookie. This is common incases where forms are dynamically added to the page. To address this case,Django provides a view decorator which forces setting of the cookie:ensure_csrf_cookie().

If you activate CSRF_USE_SESSIONS orCSRF_COOKIE_HTTPONLY, you must include the CSRF token in your HTMLand read the token from the DOM with JavaScript:

  1. {% csrf_token %}
  2. <script type="text/javascript">
  3. // using jQuery
  4. var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
  5. </script>

Setting the token on the AJAX request

Finally, you'll have to actually set the header on your AJAX request, whileprotecting the CSRF token from being sent to other domains usingsettings.crossDomain in jQuery 1.5.1and newer:

  1. function csrfSafeMethod(method) {
  2. // these HTTP methods do not require CSRF protection
  3. return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  4. }
  5. $.ajaxSetup({
  6. beforeSend: function(xhr, settings) {
  7. if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
  8. xhr.setRequestHeader("X-CSRFToken", csrftoken);
  9. }
  10. }
  11. });

If you're using AngularJS 1.1.3 and newer, it's sufficient to configure the$http provider with the cookie and header names:

  1. $httpProvider.defaults.xsrfCookieName = 'csrftoken';
  2. $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

Using CSRF in Jinja2 templates

Django's Jinja2 template backendadds {{ csrf_input }} to the context of all templates which is equivalentto {% csrf_token %} in the Django template language. For example:

  1. <form method="post">{{ csrf_input }}

The decorator method

Rather than adding CsrfViewMiddleware as a blanket protection, you can usethe csrf_protect decorator, which has exactly the same functionality, onparticular views that need the protection. It must be used both on viewsthat insert the CSRF token in the output, and on those that accept the POST formdata. (These are often the same view function, but not always).

Use of the decorator by itself is not recommended, since if you forget touse it, you will have a security hole. The 'belt and braces' strategy of usingboth is fine, and will incur minimal overhead.

  • csrfprotect(_view)
  • Decorator that provides the protection of CsrfViewMiddleware to a view.

Usage:

  1. from django.shortcuts import render
  2. from django.views.decorators.csrf import csrf_protect
  3.  
  4. @csrf_protect
  5. def my_view(request):
  6. c = {}
  7. # ...
  8. return render(request, "a_template.html", c)

If you are using class-based views, you can refer toDecorating class-based views.

Rejected requests

By default, a '403 Forbidden' response is sent to the user if an incomingrequest fails the checks performed by CsrfViewMiddleware. This shouldusually only be seen when there is a genuine Cross Site Request Forgery, orwhen, due to a programming error, the CSRF token has not been included with aPOST form.

The error page, however, is not very friendly, so you may want to provide yourown view for handling this condition. To do this, simply set theCSRF_FAILURE_VIEW setting.

CSRF failures are logged as warnings to the django.security.csrf logger.

How it works

The CSRF protection is based on the following things:

  • A CSRF cookie that is based on a random secret value, which other siteswill not have access to.

This cookie is set by CsrfViewMiddleware. It is sent with everyresponse that has called django.middleware.csrf.get_token() (thefunction used internally to retrieve the CSRF token), if it wasn't alreadyset on the request.

In order to protect against BREACH attacks, the token is not simply thesecret; a random salt is prepended to the secret and used to scramble it.

For security reasons, the value of the secret is changed each time auser logs in.

  • A hidden form field with the name 'csrfmiddlewaretoken' present in alloutgoing POST forms. The value of this field is, again, the value of thesecret, with a salt which is both added to it and used to scramble it. Thesalt is regenerated on every call to get_token() so that the form fieldvalue is changed in every such response.

This part is done by the template tag.

  • For all incoming requests that are not using HTTP GET, HEAD, OPTIONS orTRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' fieldmust be present and correct. If it isn't, the user will get a 403 error.

When validating the 'csrfmiddlewaretoken' field value, only the secret,not the full token, is compared with the secret in the cookie value.This allows the use of ever-changing tokens. While each request may use itsown token, the secret remains common to all.

This check is done by CsrfViewMiddleware.

  • In addition, for HTTPS requests, strict referer checking is done byCsrfViewMiddleware. This means that even if a subdomain can set ormodify cookies on your domain, it can't force a user to post to yourapplication since that request won't come from your own exact domain.

This also addresses a man-in-the-middle attack that's possible under HTTPSwhen using a session independent secret, due to the fact that HTTPSet-Cookie headers are (unfortunately) accepted by clients even whenthey are talking to a site under HTTPS. (Referer checking is not done forHTTP requests because the presence of the Referer header isn't reliableenough under HTTP.)

If the CSRF_COOKIE_DOMAIN setting is set, the referer is comparedagainst it. This setting supports subdomains. For example,CSRF_COOKIE_DOMAIN = '.example.com' will allow POST requests fromwww.example.com and api.example.com. If the setting is not set, thenthe referer must match the HTTP Host header.

Expanding the accepted referers beyond the current host or cookie domain canbe done with the CSRF_TRUSTED_ORIGINS setting.

This ensures that only forms that have originated from trusted domains can beused to POST data back.

It deliberately ignores GET requests (and other requests that are defined as'safe' by RFC 7231). These requests ought never to have any potentiallydangerous side effects , and so a CSRF attack with a GET request ought to beharmless. RFC 7231 defines POST, PUT, and DELETE as 'unsafe', and all othermethods are also assumed to be unsafe, for maximum protection.

The CSRF protection cannot protect against man-in-the-middle attacks, so useHTTPS withHTTP Strict Transport Security. It also assumes validation ofthe HOST header and that there aren't anycross-site scripting vulnerabilities on your site(because XSS vulnerabilities already let an attacker do anything a CSRFvulnerability allows and much worse).

Removing the Referer header

To avoid disclosing the referrer URL to third-party sites, you might wantto disable the referer on your site's <a> tags. For example, youmight use the <meta name="referrer" content="no-referrer"> tag orinclude the Referrer-Policy: no-referrer header. Due to the CSRFprotection's strict referer checking on HTTPS requests, those techniquescause a CSRF failure on requests with 'unsafe' methods. Instead, usealternatives like <a rel="noreferrer" …>" for links to third-partysites.

Caching

If the csrf_token template tag is used by a template (or theget_token function is called some other way), CsrfViewMiddleware willadd a cookie and a Vary: Cookie header to the response. This means that themiddleware will play well with the cache middleware if it is used as instructed(UpdateCacheMiddleware goes before all other middleware).

However, if you use cache decorators on individual views, the CSRF middlewarewill not yet have been able to set the Vary header or the CSRF cookie, and theresponse will be cached without either one. In this case, on any views thatwill require a CSRF token to be inserted you should use thedjango.views.decorators.csrf.csrf_protect() decorator first:

  1. from django.views.decorators.cache import cache_page
  2. from django.views.decorators.csrf import csrf_protect
  3.  
  4. @cache_page(60 * 15)
  5. @csrf_protect
  6. def my_view(request):
  7. ...

If you are using class-based views, you can refer to Decoratingclass-based views.

Testing

The CsrfViewMiddleware will usually be a big hindrance to testing viewfunctions, due to the need for the CSRF token which must be sent with every POSTrequest. For this reason, Django's HTTP client for tests has been modified toset a flag on requests which relaxes the middleware and the csrf_protectdecorator so that they no longer rejects requests. In every other respect(e.g. sending cookies etc.), they behave the same.

If, for some reason, you want the test client to perform CSRFchecks, you can create an instance of the test client that enforcesCSRF checks:

  1. >>> from django.test import Client
  2. >>> csrf_client = Client(enforce_csrf_checks=True)

Limitations

Subdomains within a site will be able to set cookies on the client for the wholedomain. By setting the cookie and using a corresponding token, subdomains willbe able to circumvent the CSRF protection. The only way to avoid this is toensure that subdomains are controlled by trusted users (or, are at least unableto set cookies). Note that even without CSRF, there are other vulnerabilities,such as session fixation, that make giving subdomains to untrusted parties a badidea, and these vulnerabilities cannot easily be fixed with current browsers.

Edge cases

Certain views can have unusual requirements that mean they don't fit the normalpattern envisaged here. A number of utilities can be useful in thesesituations. The scenarios they might be needed in are described in the followingsection.

Utilities

The examples below assume you are using function-based views. If youare working with class-based views, you can refer to Decoratingclass-based views.

  • csrfexempt(_view)[源代码]
  • This decorator marks a view as being exempt from the protection ensured bythe middleware. Example:
  1. from django.http import HttpResponse
  2. from django.views.decorators.csrf import csrf_exempt
  3.  
  4. @csrf_exempt
  5. def my_view(request):
  6. return HttpResponse('Hello world')
  • requirescsrf_token(_view)
  • Normally the csrf_token template tag will not work ifCsrfViewMiddleware.process_view or an equivalent like csrf_protecthas not run. The view decorator requires_csrf_token can be used toensure the template tag does work. This decorator works similarly tocsrf_protect, but never rejects an incoming request.

Example:

  1. from django.shortcuts import render
  2. from django.views.decorators.csrf import requires_csrf_token
  3.  
  4. @requires_csrf_token
  5. def my_view(request):
  6. c = {}
  7. # ...
  8. return render(request, "a_template.html", c)
  • ensurecsrf_cookie(_view)
  • This decorator forces a view to send the CSRF cookie.

Scenarios

CSRF protection should be disabled for just a few views

Most views requires CSRF protection, but a few do not.

Solution: rather than disabling the middleware and applying csrf_protect toall the views that need it, enable the middleware and usecsrf_exempt().

CsrfViewMiddleware.process_view not used

There are cases when CsrfViewMiddleware.process_view may not have runbefore your view is run - 404 and 500 handlers, for example - but you stillneed the CSRF token in a form.

Solution: use requires_csrf_token()

Unprotected view needs the CSRF token

There may be some views that are unprotected and have been exempted bycsrf_exempt, but still need to include the CSRF token.

Solution: use csrf_exempt() followed byrequires_csrf_token(). (i.e. requires_csrf_tokenshould be the innermost decorator).

View needs protection for one path

A view needs CSRF protection under one set of conditions only, and mustn't haveit for the rest of the time.

Solution: use csrf_exempt() for the wholeview function, and csrf_protect() for thepath within it that needs protection. Example:

  1. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  2.  
  3. @csrf_exempt
  4. def my_view(request):
  5.  
  6. @csrf_protect
  7. def protected_path(request):
  8. do_something()
  9.  
  10. if some_condition():
  11. return protected_path(request)
  12. else:
  13. do_something_else()

Page uses AJAX without any HTML form

A page makes a POST request via AJAX, and the page does not have an HTML formwith a csrf_token that would cause the required CSRF cookie to be sent.

Solution: use ensure_csrf_cookie() on theview that sends the page.

Contrib and reusable apps

Because it is possible for the developer to turn off the CsrfViewMiddleware,all relevant views in contrib apps use the csrf_protect decorator to ensurethe security of these applications against CSRF. It is recommended that thedevelopers of other reusable apps that want the same guarantees also use thecsrf_protect decorator on their views.

Settings

A number of settings can be used to control Django's CSRF behavior:

Frequently Asked Questions

Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?

No, this is by design. Without a man-in-the-middle attack, there is no way foran attacker to send a CSRF token cookie to a victim's browser, so a successfulattack would need to obtain the victim's browser's cookie via XSS or similar,in which case an attacker usually doesn't need CSRF attacks.

Some security audit tools flag this as a problem but as mentioned before, anattacker cannot steal a user's browser's CSRF cookie. "Stealing" or modifyingyour own token using Firebug, Chrome dev tools, etc. isn't a vulnerability.

Is it a problem that Django's CSRF protection isn't linked to a session by default?

No, this is by design. Not linking CSRF protection to a session allows usingthe protection on sites such as a pastebin that allow submissions fromanonymous users which don't have a session.

If you wish to store the CSRF token in the user's session, use theCSRF_USE_SESSIONS setting.

Why might a user encounter a CSRF validation failure after logging in?

For security reasons, CSRF tokens are rotated each time a user logs in. Anypage with a form generated before a login will have an old, invalid CSRF tokenand need to be reloaded. This might happen if a user uses the back button aftera login or if they log in a different browser tab.