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