csrf.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. .. _using-csrf:
  2. ===================================
  3. How to use Django's CSRF protection
  4. ===================================
  5. To take advantage of CSRF protection in your views, follow these steps:
  6. #. The CSRF middleware is activated by default in the :setting:`MIDDLEWARE`
  7. setting. If you override that setting, remember that
  8. ``'django.middleware.csrf.CsrfViewMiddleware'`` should come before any view
  9. middleware that assume that CSRF attacks have been dealt with.
  10. If you disabled it, which is not recommended, you can use
  11. :func:`~django.views.decorators.csrf.csrf_protect` on particular views
  12. you want to protect (see below).
  13. #. In any template that uses a POST form, use the :ttag:`csrf_token` tag inside
  14. the ``<form>`` element if the form is for an internal URL, e.g.:
  15. .. code-block:: html+django
  16. <form method="post">{% csrf_token %}
  17. This should not be done for POST forms that target external URLs, since
  18. that would cause the CSRF token to be leaked, leading to a vulnerability.
  19. #. In the corresponding view functions, ensure that
  20. :class:`~django.template.RequestContext` is used to render the response so
  21. that ``{% csrf_token %}`` will work properly. If you're using the
  22. :func:`~django.shortcuts.render` function, generic views, or contrib apps,
  23. you are covered already since these all use ``RequestContext``.
  24. .. _csrf-ajax:
  25. Using CSRF protection with AJAX
  26. ===============================
  27. While the above method can be used for AJAX POST requests, it has some
  28. inconveniences: you have to remember to pass the CSRF token in as POST data with
  29. every POST request. For this reason, there is an alternative method: on each
  30. XMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the
  31. :setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is
  32. often easier because many JavaScript frameworks provide hooks that allow
  33. headers to be set on every request.
  34. First, you must get the CSRF token. How to do that depends on whether or not
  35. the :setting:`CSRF_USE_SESSIONS` and :setting:`CSRF_COOKIE_HTTPONLY` settings
  36. are enabled.
  37. .. _acquiring-csrf-token-from-cookie:
  38. Acquiring the token if :setting:`CSRF_USE_SESSIONS` and :setting:`CSRF_COOKIE_HTTPONLY` are ``False``
  39. -----------------------------------------------------------------------------------------------------
  40. The recommended source for the token is the ``csrftoken`` cookie, which will be
  41. set if you've enabled CSRF protection for your views as outlined above.
  42. The CSRF token cookie is named ``csrftoken`` by default, but you can control
  43. the cookie name via the :setting:`CSRF_COOKIE_NAME` setting.
  44. You can acquire the token like this:
  45. .. code-block:: javascript
  46. function getCookie(name) {
  47. let cookieValue = null;
  48. if (document.cookie && document.cookie !== '') {
  49. const cookies = document.cookie.split(';');
  50. for (let i = 0; i < cookies.length; i++) {
  51. const cookie = cookies[i].trim();
  52. // Does this cookie string begin with the name we want?
  53. if (cookie.substring(0, name.length + 1) === (name + '=')) {
  54. cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  55. break;
  56. }
  57. }
  58. }
  59. return cookieValue;
  60. }
  61. const csrftoken = getCookie('csrftoken');
  62. The above code could be simplified by using the `JavaScript Cookie library
  63. <https://github.com/js-cookie/js-cookie/>`_ to replace ``getCookie``:
  64. .. code-block:: javascript
  65. const csrftoken = Cookies.get('csrftoken');
  66. .. note::
  67. The CSRF token is also present in the DOM in a masked form, but only if
  68. explicitly included using :ttag:`csrf_token` in a template. The cookie
  69. contains the canonical, unmasked token. The
  70. :class:`~django.middleware.csrf.CsrfViewMiddleware` will accept either.
  71. However, in order to protect against `BREACH`_ attacks, it's recommended to
  72. use a masked token.
  73. .. warning::
  74. If your view is not rendering a template containing the :ttag:`csrf_token`
  75. template tag, Django might not set the CSRF token cookie. This is common in
  76. cases where forms are dynamically added to the page. To address this case,
  77. Django provides a view decorator which forces setting of the cookie:
  78. :func:`~django.views.decorators.csrf.ensure_csrf_cookie`.
  79. .. _BREACH: https://www.breachattack.com/
  80. .. _acquiring-csrf-token-from-html:
  81. Acquiring the token if :setting:`CSRF_USE_SESSIONS` or :setting:`CSRF_COOKIE_HTTPONLY` is ``True``
  82. --------------------------------------------------------------------------------------------------
  83. If you activate :setting:`CSRF_USE_SESSIONS` or
  84. :setting:`CSRF_COOKIE_HTTPONLY`, you must include the CSRF token in your HTML
  85. and read the token from the DOM with JavaScript:
  86. .. code-block:: html+django
  87. {% csrf_token %}
  88. <script>
  89. const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
  90. </script>
  91. Setting the token on the AJAX request
  92. -------------------------------------
  93. Finally, you'll need to set the header on your AJAX request. Using the
  94. `fetch()`_ API:
  95. .. code-block:: javascript
  96. const request = new Request(
  97. /* URL */,
  98. {
  99. method: 'POST',
  100. headers: {'X-CSRFToken': csrftoken},
  101. mode: 'same-origin' // Do not send CSRF token to another domain.
  102. }
  103. );
  104. fetch(request).then(function(response) {
  105. // ...
  106. });
  107. .. _fetch(): https://developer.mozilla.org/en-US/docs/Web/API/fetch
  108. Using CSRF protection in Jinja2 templates
  109. =========================================
  110. Django's :class:`~django.template.backends.jinja2.Jinja2` template backend
  111. adds ``{{ csrf_input }}`` to the context of all templates which is equivalent
  112. to ``{% csrf_token %}`` in the Django template language. For example:
  113. .. code-block:: html+jinja
  114. <form method="post">{{ csrf_input }}
  115. Using the decorator method
  116. ==========================
  117. Rather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use
  118. the :func:`~django.views.decorators.csrf.csrf_protect` decorator, which has
  119. exactly the same functionality, on particular views that need the protection.
  120. It must be used **both** on views that insert the CSRF token in the output, and
  121. on those that accept the POST form data. (These are often the same view
  122. function, but not always).
  123. Use of the decorator by itself is **not recommended**, since if you forget to
  124. use it, you will have a security hole. The 'belt and braces' strategy of using
  125. both is fine, and will incur minimal overhead.
  126. .. _csrf-rejected-requests:
  127. Handling rejected requests
  128. ==========================
  129. By default, a '403 Forbidden' response is sent to the user if an incoming
  130. request fails the checks performed by ``CsrfViewMiddleware``. This should
  131. usually only be seen when there is a genuine Cross Site Request Forgery, or
  132. when, due to a programming error, the CSRF token has not been included with a
  133. POST form.
  134. The error page, however, is not very friendly, so you may want to provide your
  135. own view for handling this condition. To do this, set the
  136. :setting:`CSRF_FAILURE_VIEW` setting.
  137. CSRF failures are logged as warnings to the :ref:`django.security.csrf
  138. <django-security-logger>` logger.
  139. Using CSRF protection with caching
  140. ==================================
  141. If the :ttag:`csrf_token` template tag is used by a template (or the
  142. ``get_token`` function is called some other way), ``CsrfViewMiddleware`` will
  143. add a cookie and a ``Vary: Cookie`` header to the response. This means that the
  144. middleware will play well with the cache middleware if it is used as instructed
  145. (``UpdateCacheMiddleware`` goes before all other middleware).
  146. However, if you use cache decorators on individual views, the CSRF middleware
  147. will not yet have been able to set the Vary header or the CSRF cookie, and the
  148. response will be cached without either one. In this case, on any views that
  149. will require a CSRF token to be inserted you should use the
  150. :func:`django.views.decorators.csrf.csrf_protect` decorator first::
  151. from django.views.decorators.cache import cache_page
  152. from django.views.decorators.csrf import csrf_protect
  153. @cache_page(60 * 15)
  154. @csrf_protect
  155. def my_view(request): ...
  156. If you are using class-based views, you can refer to :ref:`Decorating
  157. class-based views<decorating-class-based-views>`.
  158. Testing and CSRF protection
  159. ===========================
  160. The ``CsrfViewMiddleware`` will usually be a big hindrance to testing view
  161. functions, due to the need for the CSRF token which must be sent with every POST
  162. request. For this reason, Django's HTTP client for tests has been modified to
  163. set a flag on requests which relaxes the middleware and the ``csrf_protect``
  164. decorator so that they no longer rejects requests. In every other respect
  165. (e.g. sending cookies etc.), they behave the same.
  166. If, for some reason, you *want* the test client to perform CSRF
  167. checks, you can create an instance of the test client that enforces
  168. CSRF checks:
  169. .. code-block:: pycon
  170. >>> from django.test import Client
  171. >>> csrf_client = Client(enforce_csrf_checks=True)
  172. Edge cases
  173. ==========
  174. Certain views can have unusual requirements that mean they don't fit the normal
  175. pattern envisaged here. A number of utilities can be useful in these
  176. situations. The scenarios they might be needed in are described in the following
  177. section.
  178. Disabling CSRF protection for just a few views
  179. ----------------------------------------------
  180. Most views requires CSRF protection, but a few do not.
  181. Solution: rather than disabling the middleware and applying ``csrf_protect`` to
  182. all the views that need it, enable the middleware and use
  183. :func:`~django.views.decorators.csrf.csrf_exempt`.
  184. Setting the token when ``CsrfViewMiddleware.process_view()`` is not used
  185. ------------------------------------------------------------------------
  186. There are cases when ``CsrfViewMiddleware.process_view`` may not have run
  187. before your view is run - 404 and 500 handlers, for example - but you still
  188. need the CSRF token in a form.
  189. Solution: use :func:`~django.views.decorators.csrf.requires_csrf_token`
  190. Including the CSRF token in an unprotected view
  191. -----------------------------------------------
  192. There may be some views that are unprotected and have been exempted by
  193. ``csrf_exempt``, but still need to include the CSRF token.
  194. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by
  195. :func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``
  196. should be the innermost decorator).
  197. Protecting a view for only one path
  198. -----------------------------------
  199. A view needs CSRF protection under one set of conditions only, and mustn't have
  200. it for the rest of the time.
  201. Solution: use :func:`~django.views.decorators.csrf.csrf_exempt` for the whole
  202. view function, and :func:`~django.views.decorators.csrf.csrf_protect` for the
  203. path within it that needs protection. Example::
  204. from django.views.decorators.csrf import csrf_exempt, csrf_protect
  205. @csrf_exempt
  206. def my_view(request):
  207. @csrf_protect
  208. def protected_path(request):
  209. do_something()
  210. if some_condition():
  211. return protected_path(request)
  212. else:
  213. do_something_else()
  214. Protecting a page that uses AJAX without an HTML form
  215. -----------------------------------------------------
  216. A page makes a POST request via AJAX, and the page does not have an HTML form
  217. with a :ttag:`csrf_token` that would cause the required CSRF cookie to be sent.
  218. Solution: use :func:`~django.views.decorators.csrf.ensure_csrf_cookie` on the
  219. view that sends the page.
  220. CSRF protection in reusable applications
  221. ========================================
  222. Because it is possible for the developer to turn off the ``CsrfViewMiddleware``,
  223. all relevant views in contrib apps use the ``csrf_protect`` decorator to ensure
  224. the security of these applications against CSRF. It is recommended that the
  225. developers of other reusable apps that want the same guarantees also use the
  226. ``csrf_protect`` decorator on their views.