Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

How to use Django’s CSRF protection

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

  1. The CSRF middleware is activated by default in theMIDDLEWAREsetting. 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).

  2. In any template that uses a POST form, use thecsrf_token tag insidethe<form> element if the form is for an internal URL, e.g.:

    <formmethod="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.

  3. 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 useRequestContext.

Using CSRF protection with 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 customX-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 nottheCSRF_USE_SESSIONS andCSRF_COOKIE_HTTPONLY settingsare enabled.

Acquiring the token ifCSRF_USE_SESSIONS andCSRF_COOKIE_HTTPONLY areFalse

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

The CSRF token cookie is namedcsrftoken by default, but you can controlthe cookie name via theCSRF_COOKIE_NAME setting.

You can acquire the token like this:

functiongetCookie(name){letcookieValue=null;if(document.cookie&&document.cookie!==''){constcookies=document.cookie.split(';');for(leti=0;i<cookies.length;i++){constcookie=cookies[i].trim();// Does this cookie string begin with the name we want?if(cookie.substring(0,name.length+1)===(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}returncookieValue;}constcsrftoken=getCookie('csrftoken');

The above code could be simplified by using theJavaScript Cookie library to replacegetCookie:

constcsrftoken=Cookies.get('csrftoken');

Note

The CSRF token is also present in the DOM in a masked form, but only ifexplicitly included usingcsrf_token in a template. The cookiecontains the canonical, unmasked token. TheCsrfViewMiddleware will accept either.However, in order to protect againstBREACH attacks, it’s recommended touse a masked token.

Warning

If your view is not rendering a template containing thecsrf_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().

Acquiring the token ifCSRF_USE_SESSIONS orCSRF_COOKIE_HTTPONLY isTrue

If you activateCSRF_USE_SESSIONS orCSRF_COOKIE_HTTPONLY, you must include the CSRF token in your HTMLand read the token from the DOM with #"#setting-the-token-on-the-ajax-request" title="Link to this heading">¶

Finally, you’ll need to set the header on your AJAX request. Using thefetch() API:

constrequest=newRequest(/* URL */,{method:'POST',headers:{'X-CSRFToken':csrftoken},mode:'same-origin'// Do not send CSRF token to another domain.});fetch(request).then(function(response){// ...});

Using CSRF protection in Jinja2 templates

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

<formmethod="post">{{csrf_input}}

Using the decorator method

Rather than addingCsrfViewMiddleware as a blanket protection, you can usethecsrf_protect() decorator, which hasexactly the same functionality, on particular views that need the protection.It must be usedboth on views that insert the CSRF token in the output, andon those that accept the POST form data. (These are often the same viewfunction, but not always).

Use of the decorator by itself isnot 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.

Handling rejected requests

By default, a ‘403 Forbidden’ response is sent to the user if an incomingrequest fails the checks performed byCsrfViewMiddleware. 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, set theCSRF_FAILURE_VIEW setting.

CSRF failures are logged as warnings to thedjango.security.csrf logger.

Using CSRF protection with caching

If thecsrf_token template tag is used by a template (or theget_token function is called some other way),CsrfViewMiddleware willadd a cookie and aVary: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:

fromdjango.views.decorators.cacheimportcache_pagefromdjango.views.decorators.csrfimportcsrf_protect@cache_page(60*15)@csrf_protectdefmy_view(request):...

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

Testing and CSRF protection

TheCsrfViewMiddleware 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 thecsrf_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, youwant the test client to perform CSRFchecks, you can create an instance of the test client that enforcesCSRF checks:

>>>fromdjango.testimportClient>>>csrf_client=Client(enforce_csrf_checks=True)

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.

Disabling CSRF protection for just a few views

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

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

Setting the token whenCsrfViewMiddleware.process_view() is not used

There are cases whenCsrfViewMiddleware.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: userequires_csrf_token()

Including the CSRF token in an unprotected view

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

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

Protecting a view for only one path

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

Solution: usecsrf_exempt() for the wholeview function, andcsrf_protect() for thepath within it that needs protection. Example:

fromdjango.views.decorators.csrfimportcsrf_exempt,csrf_protect@csrf_exemptdefmy_view(request):@csrf_protectdefprotected_path(request):do_something()ifsome_condition():returnprotected_path(request)else:do_something_else()

Protecting a page that uses AJAX without an HTML form

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

Solution: useensure_csrf_cookie() on theview that sends the page.

CSRF protection in reusable applications

Because it is possible for the developer to turn off theCsrfViewMiddleware,all relevant views in contrib apps use thecsrf_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.

Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 5.2):HTML |PDF |ePub
Provided byRead the Docs.


[8]ページ先頭

©2009-2025 Movatter.jp