{"title":"Cross Site Request Forgery protection","version":"3.2","locale":"en","docname":"ref/csrf","url":"/en/3.2/ref/csrf/","canonical":"https://djangodocs.dev/en/3.2/ref/csrf/","summary":"The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries . This type of attack occurs when a malicious website…","html":"<span id=\"cross-site-request-forgery-protection\"></span><h1>Cross Site Request Forgery protection<a class=\"heading-anchor\" href=\"#module-django.middleware.csrf\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>The CSRF middleware and template tag provides easy-to-use protection against\n<a class=\"reference external\" href=\"https://www.squarefree.com/securitytips/web-developers.html#CSRF\">Cross Site Request Forgeries</a>.  This type of attack occurs when a malicious\nwebsite contains a link, a form button or some JavaScript that is intended to\nperform some action on your website, using the credentials of a logged-in user\nwho visits the malicious site in their browser.  A related type of attack,\n‘login CSRF’, where an attacking site tricks a user’s browser into logging into\na site with someone else’s credentials, is also covered.</p>\n<p>The first defense against CSRF attacks is to ensure that GET requests (and other\n‘safe’ methods, as defined by <span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html#section-4.2.1\"><strong>RFC 7231 Section 4.2.1</strong></a>) are side effect free.\nRequests via ‘unsafe’ methods, such as POST, PUT, and DELETE, can then be\nprotected by following the steps below.</p>\n<section id=\"how-to-use-it\">\n<span id=\"using-csrf\"></span><h2>How to use it<a class=\"heading-anchor\" href=\"#how-to-use-it\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>To take advantage of CSRF protection in your views, follow these steps:</p>\n<ol class=\"arabic\">\n<li><p>The CSRF middleware is activated by default in the <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-MIDDLEWARE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">MIDDLEWARE</span></code></a>\nsetting. If you override that setting, remember that\n<code class=\"docutils literal notranslate\"><span class=\"pre\">'django.middleware.csrf.CsrfViewMiddleware'</span></code> should come before any view\nmiddleware that assume that CSRF attacks have been dealt with.</p>\n<p>If you disabled it, which is not recommended, you can use\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_protect()</span></code></a> on particular views\nyou want to protect (see below).</p>\n</li>\n<li><p>In any template that uses a POST form, use the <a class=\"reference internal\" href=\"/en/3.2/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> tag inside\nthe <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;form&gt;</span></code> element if the form is for an internal URL, e.g.:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">form</span> <span class=\"na\">method</span><span class=\"o\">=</span><span class=\"s\">&quot;post&quot;</span><span class=\"p\">&gt;</span><span class=\"cp\">{%</span> <span class=\"k\">csrf_token</span> <span class=\"cp\">%}</span>\n</code></pre></div>\n<p>This should not be done for POST forms that target external URLs, since\nthat would cause the CSRF token to be leaked, leading to a vulnerability.</p>\n</li>\n<li><p>In the corresponding view functions, ensure that\n<a class=\"reference internal\" href=\"/en/3.2/ref/templates/api/#django.template.RequestContext\" title=\"django.template.RequestContext\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RequestContext</span></code></a> is used to render the response so\nthat <code class=\"docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">csrf_token</span> <span class=\"pre\">%}</span></code> will work properly. If you’re using the\n<a class=\"reference internal\" href=\"/en/3.2/topics/http/shortcuts/#django.shortcuts.render\" title=\"django.shortcuts.render\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">render()</span></code></a> function, generic views, or contrib apps,\nyou are covered already since these all use <code class=\"docutils literal notranslate\"><span class=\"pre\">RequestContext</span></code>.</p></li>\n</ol>\n<section id=\"ajax\">\n<span id=\"csrf-ajax\"></span><h3>AJAX<a class=\"heading-anchor\" href=\"#ajax\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>While the above method can be used for AJAX POST requests, it has some\ninconveniences: you have to remember to pass the CSRF token in as POST data with\nevery POST request. For this reason, there is an alternative method: on each\nXMLHttpRequest, set a custom <code class=\"docutils literal notranslate\"><span class=\"pre\">X-CSRFToken</span></code> header (as specified by the\n<a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_HEADER_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_HEADER_NAME</span></code></a> setting) to the value of the CSRF token. This is\noften easier because many JavaScript frameworks provide hooks that allow\nheaders to be set on every request.</p>\n<p>First, you must get the CSRF token. How to do that depends on whether or not\nthe <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> and <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a> settings\nare enabled.</p>\n<section id=\"acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false\">\n<span id=\"acquiring-csrf-token-from-cookie\"></span><h4>Acquiring the token if <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> and <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a> are <code class=\"docutils literal notranslate\"><span class=\"pre\">False</span></code><a class=\"heading-anchor\" href=\"#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>The recommended source for the token is the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrftoken</span></code> cookie, which will be\nset if you’ve enabled CSRF protection for your views as outlined above.</p>\n<p>The CSRF token cookie is named <code class=\"docutils literal notranslate\"><span class=\"pre\">csrftoken</span></code> by default, but you can control\nthe cookie name via the <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_NAME</span></code></a> setting.</p>\n<p>You can acquire the token like this:</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"kd\">function</span><span class=\"w\"> </span><span class=\"nx\">getCookie</span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">    </span><span class=\"kd\">let</span><span class=\"w\"> </span><span class=\"nx\">cookieValue</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"kc\">null</span><span class=\"p\">;</span>\n<span class=\"w\">    </span><span class=\"k\">if</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span><span class=\"w\"> </span><span class=\"o\">&amp;&amp;</span><span class=\"w\"> </span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span><span class=\"w\"> </span><span class=\"o\">!==</span><span class=\"w\"> </span><span class=\"s1\">&#39;&#39;</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">        </span><span class=\"kd\">const</span><span class=\"w\"> </span><span class=\"nx\">cookies</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span><span class=\"p\">.</span><span class=\"nx\">split</span><span class=\"p\">(</span><span class=\"s1\">&#39;;&#39;</span><span class=\"p\">);</span>\n<span class=\"w\">        </span><span class=\"k\">for</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"kd\">let</span><span class=\"w\"> </span><span class=\"nx\">i</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"mf\">0</span><span class=\"p\">;</span><span class=\"w\"> </span><span class=\"nx\">i</span><span class=\"w\"> </span><span class=\"o\">&lt;</span><span class=\"w\"> </span><span class=\"nx\">cookies</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"p\">;</span><span class=\"w\"> </span><span class=\"nx\">i</span><span class=\"o\">++</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">            </span><span class=\"kd\">const</span><span class=\"w\"> </span><span class=\"nx\">cookie</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">cookies</span><span class=\"p\">[</span><span class=\"nx\">i</span><span class=\"p\">].</span><span class=\"nx\">trim</span><span class=\"p\">();</span>\n<span class=\"w\">            </span><span class=\"c1\">// Does this cookie string begin with the name we want?</span>\n<span class=\"w\">            </span><span class=\"k\">if</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"nx\">cookie</span><span class=\"p\">.</span><span class=\"nx\">substring</span><span class=\"p\">(</span><span class=\"mf\">0</span><span class=\"p\">,</span><span class=\"w\"> </span><span class=\"nx\">name</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"w\"> </span><span class=\"o\">+</span><span class=\"w\"> </span><span class=\"mf\">1</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"o\">===</span><span class=\"w\"> </span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"w\"> </span><span class=\"o\">+</span><span class=\"w\"> </span><span class=\"s1\">&#39;=&#39;</span><span class=\"p\">))</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">                </span><span class=\"nx\">cookieValue</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nb\">decodeURIComponent</span><span class=\"p\">(</span><span class=\"nx\">cookie</span><span class=\"p\">.</span><span class=\"nx\">substring</span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"w\"> </span><span class=\"o\">+</span><span class=\"w\"> </span><span class=\"mf\">1</span><span class=\"p\">));</span>\n<span class=\"w\">                </span><span class=\"k\">break</span><span class=\"p\">;</span>\n<span class=\"w\">            </span><span class=\"p\">}</span>\n<span class=\"w\">        </span><span class=\"p\">}</span>\n<span class=\"w\">    </span><span class=\"p\">}</span>\n<span class=\"w\">    </span><span class=\"k\">return</span><span class=\"w\"> </span><span class=\"nx\">cookieValue</span><span class=\"p\">;</span>\n<span class=\"p\">}</span>\n<span class=\"kd\">const</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">getCookie</span><span class=\"p\">(</span><span class=\"s1\">&#39;csrftoken&#39;</span><span class=\"p\">);</span>\n</code></pre></div>\n<p>The above code could be simplified by using the <a class=\"reference external\" href=\"https://github.com/js-cookie/js-cookie/\">JavaScript Cookie library</a> to replace <code class=\"docutils literal notranslate\"><span class=\"pre\">getCookie</span></code>:</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"kd\">const</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nx\">Cookies</span><span class=\"p\">.</span><span class=\"nx\">get</span><span class=\"p\">(</span><span class=\"s1\">&#39;csrftoken&#39;</span><span class=\"p\">);</span>\n</code></pre></div>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>The CSRF token is also present in the DOM, but only if explicitly included\nusing <a class=\"reference internal\" href=\"/en/3.2/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> in a template. The cookie contains the canonical\ntoken; the <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> will prefer the cookie to the token in\nthe DOM. Regardless, you’re guaranteed to have the cookie if the token is\npresent in the DOM, so you should use the cookie!</p>\n</aside>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>If your view is not rendering a template containing the <a class=\"reference internal\" href=\"/en/3.2/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a>\ntemplate tag, Django might not set the CSRF token cookie. This is common in\ncases where forms are dynamically added to the page. To address this case,\nDjango provides a view decorator which forces setting of the cookie:\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.ensure_csrf_cookie\" title=\"django.views.decorators.csrf.ensure_csrf_cookie\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">ensure_csrf_cookie()</span></code></a>.</p>\n</aside>\n</section>\n<section id=\"acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true\">\n<span id=\"acquiring-csrf-token-from-html\"></span><h4>Acquiring the token if <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> or <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a> is <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code><a class=\"heading-anchor\" href=\"#acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>If you activate <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> or\n<a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a>, you must include the CSRF token in your HTML\nand read the token from the DOM with JavaScript:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{%</span> <span class=\"k\">csrf_token</span> <span class=\"cp\">%}</span>\n<span class=\"p\">&lt;</span><span class=\"nt\">script</span><span class=\"p\">&gt;</span>\n<span class=\"kd\">const</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">querySelector</span><span class=\"p\">(</span><span class=\"s1\">&#39;[name=csrfmiddlewaretoken]&#39;</span><span class=\"p\">).</span><span class=\"nx\">value</span><span class=\"p\">;</span>\n<span class=\"p\">&lt;/</span><span class=\"nt\">script</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n</section>\n<section id=\"setting-the-token-on-the-ajax-request\">\n<h4>Setting the token on the AJAX request<a class=\"heading-anchor\" href=\"#setting-the-token-on-the-ajax-request\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Finally, you’ll need to set the header on your AJAX request. Using the\n<a class=\"reference external\" href=\"https://developer.mozilla.org/en-US/docs/Web/API/fetch\">fetch()</a> API:</p>\n<div class=\"code-block\" data-language=\"javascript\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">JavaScript</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"JavaScript code\"><code><span class=\"kd\">const</span><span class=\"w\"> </span><span class=\"nx\">request</span><span class=\"w\"> </span><span class=\"o\">=</span><span class=\"w\"> </span><span class=\"ow\">new</span><span class=\"w\"> </span><span class=\"nx\">Request</span><span class=\"p\">(</span>\n<span class=\"w\">    </span><span class=\"cm\">/* URL */</span><span class=\"p\">,</span>\n<span class=\"w\">    </span><span class=\"p\">{</span><span class=\"nx\">headers</span><span class=\"o\">:</span><span class=\"w\"> </span><span class=\"p\">{</span><span class=\"s1\">&#39;X-CSRFToken&#39;</span><span class=\"o\">:</span><span class=\"w\"> </span><span class=\"nx\">csrftoken</span><span class=\"p\">}}</span>\n<span class=\"p\">);</span>\n<span class=\"nx\">fetch</span><span class=\"p\">(</span><span class=\"nx\">request</span><span class=\"p\">,</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">    </span><span class=\"nx\">method</span><span class=\"o\">:</span><span class=\"w\"> </span><span class=\"s1\">&#39;POST&#39;</span><span class=\"p\">,</span>\n<span class=\"w\">    </span><span class=\"nx\">mode</span><span class=\"o\">:</span><span class=\"w\"> </span><span class=\"s1\">&#39;same-origin&#39;</span><span class=\"w\">  </span><span class=\"c1\">// Do not send CSRF token to another domain.</span>\n<span class=\"p\">}).</span><span class=\"nx\">then</span><span class=\"p\">(</span><span class=\"kd\">function</span><span class=\"p\">(</span><span class=\"nx\">response</span><span class=\"p\">)</span><span class=\"w\"> </span><span class=\"p\">{</span>\n<span class=\"w\">    </span><span class=\"c1\">// ...</span>\n<span class=\"p\">});</span>\n</code></pre></div>\n</section>\n</section>\n<section id=\"using-csrf-in-jinja2-templates\">\n<h3>Using CSRF in Jinja2 templates<a class=\"heading-anchor\" href=\"#using-csrf-in-jinja2-templates\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django’s <a class=\"reference internal\" href=\"/en/3.2/topics/templates/#django.template.backends.jinja2.Jinja2\" title=\"django.template.backends.jinja2.Jinja2\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Jinja2</span></code></a> template backend\nadds <code class=\"docutils literal notranslate\"><span class=\"pre\">{{</span> <span class=\"pre\">csrf_input</span> <span class=\"pre\">}}</span></code> to the context of all templates which is equivalent\nto <code class=\"docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">csrf_token</span> <span class=\"pre\">%}</span></code> in the Django template language. For example:</p>\n<div class=\"code-block\" data-language=\"html+jinja\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Html Jinja</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Html Jinja code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">form</span> <span class=\"na\">method</span><span class=\"o\">=</span><span class=\"s\">&quot;post&quot;</span><span class=\"p\">&gt;</span><span class=\"cp\">{{</span> <span class=\"nv\">csrf_input</span> <span class=\"cp\">}}</span>\n</code></pre></div>\n</section>\n<section id=\"module-django.views.decorators.csrf\">\n<span id=\"the-decorator-method\"></span><h3>The decorator method<a class=\"heading-anchor\" href=\"#module-django.views.decorators.csrf\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Rather than adding <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> as a blanket protection, you can use\nthe <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> decorator, which has exactly the same functionality, on\nparticular views that need the protection. It must be used <strong>both</strong> on views\nthat insert the CSRF token in the output, and on those that accept the POST form\ndata. (These are often the same view function, but not always).</p>\n<p>Use of the decorator by itself is <strong>not recommended</strong>, since if you forget to\nuse it, you will have a security hole. The ‘belt and braces’ strategy of using\nboth is fine, and will incur minimal overhead.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.csrf_protect\">\n<span class=\"sig-name descname\"><span class=\"pre\">csrf_protect</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.csrf_protect\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Decorator that provides the protection of <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> to a view.</p>\n<p>Usage:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.shortcuts</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">render</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_protect</span>\n\n<span class=\"nd\">@csrf_protect</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">c</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">return</span> <span class=\"n\">render</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">,</span> <span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> <span class=\"n\">c</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>If you are using class-based views, you can refer to\n<a class=\"reference internal\" href=\"/en/3.2/topics/class-based-views/intro/#id1\"><span class=\"std std-ref\">Decorating class-based views</span></a>.</p>\n</dd></dl>\n\n</section>\n</section>\n<section id=\"rejected-requests\">\n<span id=\"csrf-rejected-requests\"></span><h2>Rejected requests<a class=\"heading-anchor\" href=\"#rejected-requests\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>By default, a ‘403 Forbidden’ response is sent to the user if an incoming\nrequest fails the checks performed by <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>.  This should\nusually only be seen when there is a genuine Cross Site Request Forgery, or\nwhen, due to a programming error, the CSRF token has not been included with a\nPOST form.</p>\n<p>The error page, however, is not very friendly, so you may want to provide your\nown view for handling this condition.  To do this, set the\n<a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_FAILURE_VIEW\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_FAILURE_VIEW</span></code></a> setting.</p>\n<p>CSRF failures are logged as warnings to the <a class=\"reference internal\" href=\"/en/3.2/topics/logging/#django-security-logger\"><span class=\"std std-ref\">django.security.csrf</span></a> logger.</p>\n</section>\n<section id=\"how-it-works\">\n<span id=\"how-csrf-works\"></span><h2>How it works<a class=\"heading-anchor\" href=\"#how-it-works\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The CSRF protection is based on the following things:</p>\n<ol class=\"arabic\">\n<li><p>A CSRF cookie that is based on a random secret value, which other sites\nwill not have access to.</p>\n<p>This cookie is set by <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>. It is sent with every\nresponse that has called <code class=\"docutils literal notranslate\"><span class=\"pre\">django.middleware.csrf.get_token()</span></code> (the\nfunction used internally to retrieve the CSRF token), if it wasn’t already\nset on the request.</p>\n<p>In order to protect against <a class=\"reference external\" href=\"http://breachattack.com/\">BREACH</a> attacks, the token is not simply the\nsecret; a random mask is prepended to the secret and used to scramble it.</p>\n<p>For security reasons, the value of the secret is changed each time a\nuser logs in.</p>\n</li>\n<li><p>A hidden form field with the name ‘csrfmiddlewaretoken’ present in all\noutgoing POST forms. The value of this field is, again, the value of the\nsecret, with a mask which is both added to it and used to scramble it. The\nmask is regenerated on every call to <code class=\"docutils literal notranslate\"><span class=\"pre\">get_token()</span></code> so that the form field\nvalue is changed in every such response.</p>\n<p>This part is done by the template tag.</p>\n</li>\n<li><p>For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or\nTRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field\nmust be present and correct. If it isn’t, the user will get a 403 error.</p>\n<p>When validating the ‘csrfmiddlewaretoken’ field value, only the secret,\nnot the full token, is compared with the secret in the cookie value.\nThis allows the use of ever-changing tokens. While each request may use its\nown token, the secret remains common to all.</p>\n<p>This check is done by <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>.</p>\n</li>\n<li><p>In addition, for HTTPS requests, strict referer checking is done by\n<code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>. This means that even if a subdomain can set or\nmodify cookies on your domain, it can’t force a user to post to your\napplication since that request won’t come from your own exact domain.</p>\n<p>This also addresses a man-in-the-middle attack that’s possible under HTTPS\nwhen using a session independent secret, due to the fact that HTTP\n<code class=\"docutils literal notranslate\"><span class=\"pre\">Set-Cookie</span></code> headers are (unfortunately) accepted by clients even when\nthey are talking to a site under HTTPS. (Referer checking is not done for\nHTTP requests because the presence of the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header isn’t reliable\nenough under HTTP.)</p>\n<p>If the <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_DOMAIN\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_DOMAIN</span></code></a> setting is set, the referer is compared\nagainst it. You can allow cross-subdomain requests by including a leading\ndot. For example, <code class=\"docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_DOMAIN</span> <span class=\"pre\">=</span> <span class=\"pre\">'.example.com'</span></code> will allow POST\nrequests from <code class=\"docutils literal notranslate\"><span class=\"pre\">www.example.com</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">api.example.com</span></code>. If the setting is\nnot set, then the referer must match the HTTP <code class=\"docutils literal notranslate\"><span class=\"pre\">Host</span></code> header.</p>\n<p>Expanding the accepted referers beyond the current host or cookie domain can\nbe done with the <a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_TRUSTED_ORIGINS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_TRUSTED_ORIGINS</span></code></a> setting.</p>\n</li>\n</ol>\n<p>This ensures that only forms that have originated from trusted domains can be\nused to POST data back.</p>\n<p>It deliberately ignores GET requests (and other requests that are defined as\n‘safe’ by <span class=\"target\" id=\"index-1\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html#section-4.2.1\"><strong>RFC 7231 Section 4.2.1</strong></a>). These requests ought never to have any\npotentially dangerous side effects, and so a CSRF attack with a GET request\nought to be harmless. <span class=\"target\" id=\"index-2\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc7231.html#section-4.2.1\"><strong>RFC 7231 Section 4.2.1</strong></a> defines POST, PUT, and DELETE\nas ‘unsafe’, and all other methods are also assumed to be unsafe, for maximum\nprotection.</p>\n<p>The CSRF protection cannot protect against man-in-the-middle attacks, so use\n<a class=\"reference internal\" href=\"/en/3.2/topics/security/#security-recommendation-ssl\"><span class=\"std std-ref\">HTTPS</span></a> with\n<a class=\"reference internal\" href=\"/en/3.2/ref/middleware/#http-strict-transport-security\"><span class=\"std std-ref\">HTTP Strict Transport Security</span></a>. It also assumes <a class=\"reference internal\" href=\"/en/3.2/topics/security/#host-headers-virtual-hosting\"><span class=\"std std-ref\">validation of\nthe HOST header</span></a> and that there aren’t any\n<a class=\"reference internal\" href=\"/en/3.2/topics/security/#cross-site-scripting\"><span class=\"std std-ref\">cross-site scripting vulnerabilities</span></a> on your site\n(because XSS vulnerabilities already let an attacker do anything a CSRF\nvulnerability allows and much worse).</p>\n<aside class=\"admonition-removing-the-referer-header admonition\">\n<p class=\"admonition-title\">Removing the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referer</span></code> header</p>\n<p>To avoid disclosing the referrer URL to third-party sites, you might want\nto <a class=\"reference external\" href=\"https://www.w3.org/TR/referrer-policy/#referrer-policy-delivery\">disable the referer</a> on your site’s <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;a&gt;</span></code> tags. For example, you\nmight use the <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;meta</span> <span class=\"pre\">name=&quot;referrer&quot;</span> <span class=\"pre\">content=&quot;no-referrer&quot;&gt;</span></code> tag or\ninclude the <code class=\"docutils literal notranslate\"><span class=\"pre\">Referrer-Policy:</span> <span class=\"pre\">no-referrer</span></code> header. Due to the CSRF\nprotection’s strict referer checking on HTTPS requests, those techniques\ncause a CSRF failure on requests with ‘unsafe’ methods. Instead, use\nalternatives like <code class=\"docutils literal notranslate\"><span class=\"pre\">&lt;a</span> <span class=\"pre\">rel=&quot;noreferrer&quot;</span> <span class=\"pre\">...&gt;&quot;</span></code> for links to third-party\nsites.</p>\n</aside>\n</section>\n<section id=\"caching\">\n<h2>Caching<a class=\"heading-anchor\" href=\"#caching\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>If the <a class=\"reference internal\" href=\"/en/3.2/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> template tag is used by a template (or the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">get_token</span></code> function is called some other way), <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> will\nadd a cookie and a <code class=\"docutils literal notranslate\"><span class=\"pre\">Vary:</span> <span class=\"pre\">Cookie</span></code> header to the response. This means that the\nmiddleware will play well with the cache middleware if it is used as instructed\n(<code class=\"docutils literal notranslate\"><span class=\"pre\">UpdateCacheMiddleware</span></code> goes before all other middleware).</p>\n<p>However, if you use cache decorators on individual views, the CSRF middleware\nwill not yet have been able to set the Vary header or the CSRF cookie, and the\nresponse will be cached without either one. In this case, on any views that\nwill require a CSRF token to be inserted you should use the\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">django.views.decorators.csrf.csrf_protect()</span></code></a> decorator first:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.cache</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">cache_page</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_protect</span>\n\n<span class=\"nd\">@cache_page</span><span class=\"p\">(</span><span class=\"mi\">60</span> <span class=\"o\">*</span> <span class=\"mi\">15</span><span class=\"p\">)</span>\n<span class=\"nd\">@csrf_protect</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>If you are using class-based views, you can refer to <a class=\"reference internal\" href=\"/en/3.2/topics/class-based-views/intro/#id1\"><span class=\"std std-ref\">Decorating\nclass-based views</span></a>.</p>\n</section>\n<section id=\"testing\">\n<h2>Testing<a class=\"heading-anchor\" href=\"#testing\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>The <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code> will usually be a big hindrance to testing view\nfunctions, due to the need for the CSRF token which must be sent with every POST\nrequest.  For this reason, Django’s HTTP client for tests has been modified to\nset a flag on requests which relaxes the middleware and the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code>\ndecorator so that they no longer rejects requests.  In every other respect\n(e.g. sending cookies etc.), they behave the same.</p>\n<p>If, for some reason, you <em>want</em> the test client to perform CSRF\nchecks, you can create an instance of the test client that enforces\nCSRF checks:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"gp\">&gt;&gt;&gt; </span><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.test</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">Client</span>\n<span class=\"gp\">&gt;&gt;&gt; </span><span class=\"n\">csrf_client</span> <span class=\"o\">=</span> <span class=\"n\">Client</span><span class=\"p\">(</span><span class=\"n\">enforce_csrf_checks</span><span class=\"o\">=</span><span class=\"kc\">True</span><span class=\"p\">)</span>\n</code></pre></div>\n</section>\n<section id=\"limitations\">\n<span id=\"csrf-limitations\"></span><h2>Limitations<a class=\"heading-anchor\" href=\"#limitations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Subdomains within a site will be able to set cookies on the client for the whole\ndomain.  By setting the cookie and using a corresponding token, subdomains will\nbe able to circumvent the CSRF protection.  The only way to avoid this is to\nensure that subdomains are controlled by trusted users (or, are at least unable\nto set cookies).  Note that even without CSRF, there are other vulnerabilities,\nsuch as session fixation, that make giving subdomains to untrusted parties a bad\nidea, and these vulnerabilities cannot easily be fixed with current browsers.</p>\n</section>\n<section id=\"edge-cases\">\n<h2>Edge cases<a class=\"heading-anchor\" href=\"#edge-cases\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Certain views can have unusual requirements that mean they don’t fit the normal\npattern envisaged here. A number of utilities can be useful in these\nsituations. The scenarios they might be needed in are described in the following\nsection.</p>\n<section id=\"utilities\">\n<h3>Utilities<a class=\"heading-anchor\" href=\"#utilities\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The examples below assume you are using function-based views. If you\nare working with class-based views, you can refer to <a class=\"reference internal\" href=\"/en/3.2/topics/class-based-views/intro/#id1\"><span class=\"std std-ref\">Decorating\nclass-based views</span></a>.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.csrf_exempt\">\n<span class=\"sig-name descname\"><span class=\"pre\">csrf_exempt</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.csrf_exempt\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This decorator marks a view as being exempt from the protection ensured by\nthe middleware. Example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.http</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">HttpResponse</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_exempt</span>\n\n<span class=\"nd\">@csrf_exempt</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"k\">return</span> <span class=\"n\">HttpResponse</span><span class=\"p\">(</span><span class=\"s1\">&#39;Hello world&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.requires_csrf_token\">\n<span class=\"sig-name descname\"><span class=\"pre\">requires_csrf_token</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.requires_csrf_token\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Normally the <a class=\"reference internal\" href=\"/en/3.2/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> template tag will not work if\n<code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware.process_view</span></code> or an equivalent like <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code>\nhas not run. The view decorator <code class=\"docutils literal notranslate\"><span class=\"pre\">requires_csrf_token</span></code> can be used to\nensure the template tag does work. This decorator works similarly to\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code>, but never rejects an incoming request.</p>\n<p>Example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.shortcuts</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">render</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">requires_csrf_token</span>\n\n<span class=\"nd\">@requires_csrf_token</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n    <span class=\"n\">c</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">return</span> <span class=\"n\">render</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">,</span> <span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> <span class=\"n\">c</span><span class=\"p\">)</span>\n</code></pre></div>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.views.decorators.csrf.ensure_csrf_cookie\">\n<span class=\"sig-name descname\"><span class=\"pre\">ensure_csrf_cookie</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">view</span></span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.views.decorators.csrf.ensure_csrf_cookie\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This decorator forces a view to send the CSRF cookie.</p>\n</dd></dl>\n\n</section>\n<section id=\"scenarios\">\n<h3>Scenarios<a class=\"heading-anchor\" href=\"#scenarios\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<section id=\"csrf-protection-should-be-disabled-for-just-a-few-views\">\n<h4>CSRF protection should be disabled for just a few views<a class=\"heading-anchor\" href=\"#csrf-protection-should-be-disabled-for-just-a-few-views\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Most views requires CSRF protection, but a few do not.</p>\n<p>Solution: rather than disabling the middleware and applying <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> to\nall the views that need it, enable the middleware and use\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a>.</p>\n</section>\n<section id=\"csrfviewmiddleware-process-view-not-used\">\n<h4>CsrfViewMiddleware.process_view not used<a class=\"heading-anchor\" href=\"#csrfviewmiddleware-process-view-not-used\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>There are cases when <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware.process_view</span></code> may not have run\nbefore your view is run - 404 and 500 handlers, for example - but you still\nneed the CSRF token in a form.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.requires_csrf_token\" title=\"django.views.decorators.csrf.requires_csrf_token\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">requires_csrf_token()</span></code></a></p>\n</section>\n<section id=\"unprotected-view-needs-the-csrf-token\">\n<h4>Unprotected view needs the CSRF token<a class=\"heading-anchor\" href=\"#unprotected-view-needs-the-csrf-token\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>There may be some views that are unprotected and have been exempted by\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_exempt</span></code>, but still need to include the CSRF token.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a> followed by\n<a class=\"reference internal\" href=\"#django.views.decorators.csrf.requires_csrf_token\" title=\"django.views.decorators.csrf.requires_csrf_token\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">requires_csrf_token()</span></code></a>. (i.e. <code class=\"docutils literal notranslate\"><span class=\"pre\">requires_csrf_token</span></code>\nshould be the innermost decorator).</p>\n</section>\n<section id=\"view-needs-protection-for-one-path\">\n<h4>View needs protection for one path<a class=\"heading-anchor\" href=\"#view-needs-protection-for-one-path\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>A view needs CSRF protection under one set of conditions only, and mustn’t have\nit for the rest of the time.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_exempt\" title=\"django.views.decorators.csrf.csrf_exempt\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_exempt()</span></code></a> for the whole\nview function, and <a class=\"reference internal\" href=\"#django.views.decorators.csrf.csrf_protect\" title=\"django.views.decorators.csrf.csrf_protect\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">csrf_protect()</span></code></a> for the\npath within it that needs protection. Example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.views.decorators.csrf</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_exempt</span><span class=\"p\">,</span> <span class=\"n\">csrf_protect</span>\n\n<span class=\"nd\">@csrf_exempt</span>\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">my_view</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n\n    <span class=\"nd\">@csrf_protect</span>\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">protected_path</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">):</span>\n        <span class=\"n\">do_something</span><span class=\"p\">()</span>\n\n    <span class=\"k\">if</span> <span class=\"n\">some_condition</span><span class=\"p\">():</span>\n       <span class=\"k\">return</span> <span class=\"n\">protected_path</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">)</span>\n    <span class=\"k\">else</span><span class=\"p\">:</span>\n       <span class=\"n\">do_something_else</span><span class=\"p\">()</span>\n</code></pre></div>\n</section>\n<section id=\"page-uses-ajax-without-any-html-form\">\n<h4>Page uses AJAX without any HTML form<a class=\"heading-anchor\" href=\"#page-uses-ajax-without-any-html-form\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>A page makes a POST request via AJAX, and the page does not have an HTML form\nwith a <a class=\"reference internal\" href=\"/en/3.2/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">csrf_token</span></code></a> that would cause the required CSRF cookie to be sent.</p>\n<p>Solution: use <a class=\"reference internal\" href=\"#django.views.decorators.csrf.ensure_csrf_cookie\" title=\"django.views.decorators.csrf.ensure_csrf_cookie\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">ensure_csrf_cookie()</span></code></a> on the\nview that sends the page.</p>\n</section>\n</section>\n</section>\n<section id=\"contrib-and-reusable-apps\">\n<h2>Contrib and reusable apps<a class=\"heading-anchor\" href=\"#contrib-and-reusable-apps\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Because it is possible for the developer to turn off the <code class=\"docutils literal notranslate\"><span class=\"pre\">CsrfViewMiddleware</span></code>,\nall relevant views in contrib apps use the <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> decorator to ensure\nthe security of these applications against CSRF.  It is recommended that the\ndevelopers of other reusable apps that want the same guarantees also use the\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_protect</span></code> decorator on their views.</p>\n</section>\n<section id=\"settings\">\n<h2>Settings<a class=\"heading-anchor\" href=\"#settings\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>A number of settings can be used to control Django’s CSRF behavior:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_AGE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_AGE</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_DOMAIN\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_DOMAIN</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_HTTPONLY</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_NAME</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_PATH\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_PATH</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_SAMESITE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_SAMESITE</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_COOKIE_SECURE</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_FAILURE_VIEW\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_FAILURE_VIEW</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_HEADER_NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_HEADER_NAME</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_TRUSTED_ORIGINS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_TRUSTED_ORIGINS</span></code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a></p></li>\n</ul>\n</section>\n<section id=\"frequently-asked-questions\">\n<h2>Frequently Asked Questions<a class=\"heading-anchor\" href=\"#frequently-asked-questions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability\">\n<h3>Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?<a class=\"heading-anchor\" href=\"#is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>No, this is by design. Without a man-in-the-middle attack, there is no way for\nan attacker to send a CSRF token cookie to a victim’s browser, so a successful\nattack would need to obtain the victim’s browser’s cookie via XSS or similar,\nin which case an attacker usually doesn’t need CSRF attacks.</p>\n<p>Some security audit tools flag this as a problem but as mentioned before, an\nattacker cannot steal a user’s browser’s CSRF cookie. “Stealing” or modifying\n<em>your own</em> token using Firebug, Chrome dev tools, etc. isn’t a vulnerability.</p>\n</section>\n<section id=\"is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default\">\n<h3>Is it a problem that Django’s CSRF protection isn’t linked to a session by default?<a class=\"heading-anchor\" href=\"#is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>No, this is by design. Not linking CSRF protection to a session allows using\nthe protection on sites such as a <em>pastebin</em> that allow submissions from\nanonymous users which don’t have a session.</p>\n<p>If you wish to store the CSRF token in the user’s session, use the\n<a class=\"reference internal\" href=\"/en/3.2/ref/settings/#std-setting-CSRF_USE_SESSIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">CSRF_USE_SESSIONS</span></code></a> setting.</p>\n</section>\n<section id=\"why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in\">\n<h3>Why might a user encounter a CSRF validation failure after logging in?<a class=\"heading-anchor\" href=\"#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>For security reasons, CSRF tokens are rotated each time a user logs in. Any\npage with a form generated before a login will have an old, invalid CSRF token\nand need to be reloaded. This might happen if a user uses the back button after\na login or if they log in a different browser tab.</p>\n</section>\n</section>","rootId":"module-django.middleware.csrf","toc":[{"title":"How to use it","anchor":"how-to-use-it","children":[{"title":"AJAX","anchor":"ajax","children":[{"title":"Acquiring the token if CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False","anchor":"acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false","children":[]},{"title":"Acquiring the token if CSRF_USE_SESSIONS or CSRF_COOKIE_HTTPONLY is True","anchor":"acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true","children":[]},{"title":"Setting the token on the AJAX request","anchor":"setting-the-token-on-the-ajax-request","children":[]}]},{"title":"Using CSRF in Jinja2 templates","anchor":"using-csrf-in-jinja2-templates","children":[]},{"title":"The decorator method","anchor":"module-django.views.decorators.csrf","children":[]}]},{"title":"Rejected requests","anchor":"rejected-requests","children":[]},{"title":"How it works","anchor":"how-it-works","children":[]},{"title":"Caching","anchor":"caching","children":[]},{"title":"Testing","anchor":"testing","children":[]},{"title":"Limitations","anchor":"limitations","children":[]},{"title":"Edge cases","anchor":"edge-cases","children":[{"title":"Utilities","anchor":"utilities","children":[]},{"title":"Scenarios","anchor":"scenarios","children":[{"title":"CSRF protection should be disabled for just a few views","anchor":"csrf-protection-should-be-disabled-for-just-a-few-views","children":[]},{"title":"CsrfViewMiddleware.process_view not used","anchor":"csrfviewmiddleware-process-view-not-used","children":[]},{"title":"Unprotected view needs the CSRF token","anchor":"unprotected-view-needs-the-csrf-token","children":[]},{"title":"View needs protection for one path","anchor":"view-needs-protection-for-one-path","children":[]},{"title":"Page uses AJAX without any HTML form","anchor":"page-uses-ajax-without-any-html-form","children":[]}]}]},{"title":"Contrib and reusable apps","anchor":"contrib-and-reusable-apps","children":[]},{"title":"Settings","anchor":"settings","children":[]},{"title":"Frequently Asked Questions","anchor":"frequently-asked-questions","children":[{"title":"Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?","anchor":"is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability","children":[]},{"title":"Is it a problem that Django’s CSRF protection isn’t linked to a session by default?","anchor":"is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default","children":[]},{"title":"Why might a user encounter a CSRF validation failure after logging in?","anchor":"why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in","children":[]}]}],"breadcrumbs":[{"docname":"ref/index","title":"API Reference","url":"/en/3.2/ref/"}],"prev":{"docname":"ref/contrib/syndication","title":"The syndication feed framework","url":"/en/3.2/ref/contrib/syndication/"},"next":{"docname":"ref/databases","title":"Databases","url":"/en/3.2/ref/databases/"},"formats":{"html":"/en/3.2/ref/csrf/","markdown":"/en/3.2/ref/csrf.md","json":"/en/3.2/ref/csrf.json"},"source":"https://github.com/django/django/blob/stable/3.2.x/docs/ref/csrf.txt","official":"https://docs.djangoproject.com/en/3.2/ref/csrf/","inVersions":["dev","6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9","1.8"],"inLocales":["en","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}