Cross Site Request Forgery protection

    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.

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

    • The CSRF middleware is activated by default in the setting. 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 tag insidethe <form> element if the form is for an internal URL, e.g.:

    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 the function, generic views, or contrib apps,you are covered already since these all use RequestContext.

    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 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. var cookie = cookies[i].trim();
    6. // Does this cookie string begin with the name we want?
    7. if (cookie.substring(0, name.length + 1) === (name + '=')) {
    8. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    9. break;
    10. }
    11. }
    12. }
    13. return cookieValue;
    14. }
    15. var csrftoken = getCookie('csrftoken');

    The above code could be simplified by using the 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 template 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 or, 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 using in jQuery 1.5.1and newer:

    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 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 }}

    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)

    Rejected requests

    By default, a '403 Forbidden' response is sent to the user if an incomingrequest fails the checks performed by . 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 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 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.

    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 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. 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 with. It also assumes validation ofthe HOST header and that there aren't any 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.

    If the 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:

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

    Testing

    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.

    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 .

    • 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 template tag will not work if 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.

    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 by. (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 for the wholeview function, and csrf_protect() for thepath within it that needs protection. Example:

    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 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:

    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.

    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 the setting.

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