{"title":"Cross Site Request Forgery protection","version":"1.8","locale":"en","docname":"ref/csrf","url":"/en/1.8/ref/csrf/","canonical":"https://djangodocs.dev/en/1.8/ref/csrf/","summary":"The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries.","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=\"http://www.squarefree.com/securitytips/web-developers.html#CSRF\">Cross Site Request Forgeries</a>.  This type of attack occurs when a malicious\nWeb site contains a link, a form button or some JavaScript that is intended to\nperform some action on your Web site, 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 9.1.1 Safe Methods, HTTP 1.1,\n<span class=\"target\" id=\"index-0\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc2616.html#section-9.1.1\"><strong>RFC 2616 Section 9.1.1</strong></a>) are side-effect free. Requests via ‘unsafe’ methods,\nsuch as POST, PUT and DELETE, can then be protected by following the steps\nbelow.</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\n<a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-MIDDLEWARE_CLASSES\"><code class=\"xref std std-setting docutils literal notranslate\">MIDDLEWARE_CLASSES</code></a> setting. If you override that setting, remember\nthat <code class=\"docutils literal notranslate\">'django.middleware.csrf.CsrfViewMiddleware'</code> should come before any\nview middleware 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\">csrf_protect()</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/1.8/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\">csrf_token</code></a> tag inside\nthe <code class=\"docutils literal notranslate\">&lt;form&gt;</code> element if the form is for an internal URL, e.g.:</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=\"o\">&lt;</span>form action<span class=\"o\">=</span><span class=\"s2\">&quot;&quot;</span> method<span class=\"o\">=</span><span class=\"s2\">&quot;post&quot;</span><span class=\"o\">&gt;</span><span class=\"p\">{</span><span class=\"o\">%</span> csrf_token <span class=\"o\">%</span><span class=\"p\">}</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 the\n<code class=\"docutils literal notranslate\">'django.template.context_processors.csrf'</code> context processor is\nbeing used. Usually, this can be done in one of two ways:</p>\n<ol class=\"arabic\">\n<li><p>Use RequestContext, which always uses\n<code class=\"docutils literal notranslate\">'django.template.context_processors.csrf'</code> (no matter what template\ncontext processors are configured in the <a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\">TEMPLATES</code></a> setting).\nIf you are using generic views or contrib apps, you are covered already,\nsince these apps use RequestContext throughout.</p></li>\n<li><p>Manually import and use the processor to generate the CSRF token and\nadd it to the template context. e.g.:</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=\"nn\">django.shortcuts</span> <span class=\"kn\">import</span> render_to_response\n<span class=\"kn\">from</span> <span class=\"nn\">django.template.context_processors</span> <span class=\"kn\">import</span> csrf\n\n<span class=\"k\">def</span> <span class=\"nf\">my_view</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n    c <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    c<span class=\"o\">.</span>update<span class=\"p\">(</span>csrf<span class=\"p\">(</span>request<span class=\"p\">))</span>\n    <span class=\"c1\"># ... view code here</span>\n    <span class=\"k\">return</span> render_to_response<span class=\"p\">(</span><span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> c<span class=\"p\">)</span>\n</code></pre></div>\n<p>You may want to write your own\n<a class=\"reference internal\" href=\"/en/1.8/topics/http/shortcuts/#django.shortcuts.render_to_response\" title=\"django.shortcuts.render_to_response\"><code class=\"xref py py-func docutils literal notranslate\">render_to_response()</code></a> wrapper that takes care\nof this step for you.</p>\n</li>\n</ol>\n</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\">X-CSRFToken</code> header to the value of the CSRF\ntoken. This is often easier, because many JavaScript frameworks provide hooks\nthat allow headers to be set on every request.</p>\n<p>As a first step, you must get the CSRF token itself. The recommended source for\nthe token is the <code class=\"docutils literal notranslate\">csrftoken</code> cookie, which will be set if you’ve enabled CSRF\nprotection for your views as outlined above.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>The CSRF token cookie is named <code class=\"docutils literal notranslate\">csrftoken</code> by default, but you can control\nthe cookie name via the <a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_NAME</code></a> setting.</p>\n</aside>\n<p>Acquiring the token is straightforward:</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=\"c1\">// using jQuery</span>\n<span class=\"kd\">function</span> <span class=\"nx\">getCookie</span><span class=\"p\">(</span><span class=\"nx\">name</span><span class=\"p\">)</span> <span class=\"p\">{</span>\n    <span class=\"kd\">var</span> <span class=\"nx\">cookieValue</span> <span class=\"o\">=</span> <span class=\"kc\">null</span><span class=\"p\">;</span>\n    <span class=\"k\">if</span> <span class=\"p\">(</span><span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span> <span class=\"o\">&amp;&amp;</span> <span class=\"nb\">document</span><span class=\"p\">.</span><span class=\"nx\">cookie</span> <span class=\"o\">!=</span> <span class=\"s1\">&#39;&#39;</span><span class=\"p\">)</span> <span class=\"p\">{</span>\n        <span class=\"kd\">var</span> <span class=\"nx\">cookies</span> <span class=\"o\">=</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=\"k\">for</span> <span class=\"p\">(</span><span class=\"kd\">var</span> <span class=\"nx\">i</span> <span class=\"o\">=</span> <span class=\"mf\">0</span><span class=\"p\">;</span> <span class=\"nx\">i</span> <span class=\"o\">&lt;</span> <span class=\"nx\">cookies</span><span class=\"p\">.</span><span class=\"nx\">length</span><span class=\"p\">;</span> <span class=\"nx\">i</span><span class=\"o\">++</span><span class=\"p\">)</span> <span class=\"p\">{</span>\n            <span class=\"kd\">var</span> <span class=\"nx\">cookie</span> <span class=\"o\">=</span> <span class=\"nx\">jQuery</span><span class=\"p\">.</span><span class=\"nx\">trim</span><span class=\"p\">(</span><span class=\"nx\">cookies</span><span class=\"p\">[</span><span class=\"nx\">i</span><span class=\"p\">]);</span>\n            <span class=\"c1\">// Does this cookie string begin with the name we want?</span>\n            <span class=\"k\">if</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=\"nx\">name</span><span class=\"p\">.</span><span class=\"nx\">length</span> <span class=\"o\">+</span> <span class=\"mf\">1</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"p\">(</span><span class=\"nx\">name</span> <span class=\"o\">+</span> <span class=\"s1\">&#39;=&#39;</span><span class=\"p\">))</span> <span class=\"p\">{</span>\n                <span class=\"nx\">cookieValue</span> <span class=\"o\">=</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=\"o\">+</span> <span class=\"mf\">1</span><span class=\"p\">));</span>\n                <span class=\"k\">break</span><span class=\"p\">;</span>\n            <span class=\"p\">}</span>\n        <span class=\"p\">}</span>\n    <span class=\"p\">}</span>\n    <span class=\"k\">return</span> <span class=\"nx\">cookieValue</span><span class=\"p\">;</span>\n<span class=\"p\">}</span>\n<span class=\"kd\">var</span> <span class=\"nx\">csrftoken</span> <span class=\"o\">=</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\">getCookie</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\">var</span> <span class=\"nx\">csrftoken</span> <span class=\"o\">=</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/1.8/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\">csrf_token</code></a> in a template. The cookie contains the canonical\ntoken; the <code class=\"docutils literal notranslate\">CsrfViewMiddleware</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/1.8/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\">csrf_token</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\">ensure_csrf_cookie()</code></a>.</p>\n</aside>\n<p>Finally, you’ll have to actually set the header on your AJAX request, while\nprotecting the CSRF token from being sent to other domains using\n<a class=\"reference external\" href=\"http://api.jquery.com/jQuery.ajax\">settings.crossDomain</a> in jQuery 1.5.1 and\nnewer:</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=\"nx\">csrfSafeMethod</span><span class=\"p\">(</span><span class=\"nx\">method</span><span class=\"p\">)</span> <span class=\"p\">{</span>\n    <span class=\"c1\">// these HTTP methods do not require CSRF protection</span>\n    <span class=\"k\">return</span> <span class=\"p\">(</span><span class=\"sr\">/^(GET|HEAD|OPTIONS|TRACE)$/</span><span class=\"p\">.</span><span class=\"nx\">test</span><span class=\"p\">(</span><span class=\"nx\">method</span><span class=\"p\">));</span>\n<span class=\"p\">}</span>\n<span class=\"nx\">$</span><span class=\"p\">.</span><span class=\"nx\">ajaxSetup</span><span class=\"p\">({</span>\n    <span class=\"nx\">beforeSend</span><span class=\"o\">:</span> <span class=\"kd\">function</span><span class=\"p\">(</span><span class=\"nx\">xhr</span><span class=\"p\">,</span> <span class=\"nx\">settings</span><span class=\"p\">)</span> <span class=\"p\">{</span>\n        <span class=\"k\">if</span> <span class=\"p\">(</span><span class=\"o\">!</span><span class=\"nx\">csrfSafeMethod</span><span class=\"p\">(</span><span class=\"nx\">settings</span><span class=\"p\">.</span><span class=\"nx\">type</span><span class=\"p\">)</span> <span class=\"o\">&amp;&amp;</span> <span class=\"o\">!</span><span class=\"k\">this</span><span class=\"p\">.</span><span class=\"nx\">crossDomain</span><span class=\"p\">)</span> <span class=\"p\">{</span>\n            <span class=\"nx\">xhr</span><span class=\"p\">.</span><span class=\"nx\">setRequestHeader</span><span class=\"p\">(</span><span class=\"s2\">&quot;X-CSRFToken&quot;</span><span class=\"p\">,</span> <span class=\"nx\">csrftoken</span><span class=\"p\">);</span>\n        <span class=\"p\">}</span>\n    <span class=\"p\">}</span>\n<span class=\"p\">});</span>\n</code></pre></div>\n</section>\n<section id=\"other-template-engines\">\n<h3>Other template engines<a class=\"heading-anchor\" href=\"#other-template-engines\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>When using a different template engine than Django’s built-in engine, you can\nset the token in your forms manually after making sure it’s available in the\ntemplate context.</p>\n<p>For example, in the Jinja2 template language, your form could contain the\nfollowing:</p>\n<div class=\"code-block\" data-language=\"html\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Html</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 code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">div</span> <span class=\"na\">style</span><span class=\"o\">=</span><span class=\"s\">&quot;display:none&quot;</span><span class=\"p\">&gt;</span>\n    <span class=\"p\">&lt;</span><span class=\"nt\">input</span> <span class=\"na\">type</span><span class=\"o\">=</span><span class=\"s\">&quot;hidden&quot;</span> <span class=\"na\">name</span><span class=\"o\">=</span><span class=\"s\">&quot;csrfmiddlewaretoken&quot;</span> <span class=\"na\">value</span><span class=\"o\">=</span><span class=\"s\">&quot;{{ csrf_token }}&quot;</span><span class=\"p\">&gt;</span>\n<span class=\"p\">&lt;/</span><span class=\"nt\">div</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n<p>You can use JavaScript similar to the <a class=\"reference internal\" href=\"#csrf-ajax\"><span class=\"std std-ref\">AJAX code</span></a> above to get\nthe value of the CSRF token.</p>\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\">CsrfViewMiddleware</code> as a blanket protection, you can use\nthe <code class=\"docutils literal notranslate\">csrf_protect</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\">csrf_protect</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">view</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\">CsrfViewMiddleware</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=\"nn\">django.views.decorators.csrf</span> <span class=\"kn\">import</span> csrf_protect\n<span class=\"kn\">from</span> <span class=\"nn\">django.shortcuts</span> <span class=\"kn\">import</span> render\n\n<span class=\"nd\">@csrf_protect</span>\n<span class=\"k\">def</span> <span class=\"nf\">my_view</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n    c <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">return</span> render<span class=\"p\">(</span>request<span class=\"p\">,</span> <span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> c<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/1.8/topics/class-based-views/intro/#id2\"><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<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\">CsrfViewMiddleware</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, simply set the\n<a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_FAILURE_VIEW\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_FAILURE_VIEW</code></a> setting.</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 set to a random value (a session independent nonce, as\nit is called), which other sites will not have access to.</p>\n<p>This cookie is set by <code class=\"docutils literal notranslate\">CsrfViewMiddleware</code>.  It is meant to be permanent,\nbut since there is no way to set a cookie that never expires, it is sent with\nevery response that has called <code class=\"docutils literal notranslate\">django.middleware.csrf.get_token()</code>\n(the function used internally to retrieve the CSRF token).</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 the value of the CSRF\ncookie.</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>This check is done by <code class=\"docutils literal notranslate\">CsrfViewMiddleware</code>.</p>\n</li>\n<li><p>In addition, for HTTPS requests, strict referer checking is done by\n<code class=\"docutils literal notranslate\">CsrfViewMiddleware</code>.  This is necessary to address a Man-In-The-Middle\nattack that is possible under HTTPS when using a session independent nonce,\ndue to the fact that HTTP ‘Set-Cookie’ headers are (unfortunately) accepted\nby clients that are talking to a site under HTTPS.  (Referer checking is not\ndone for HTTP requests because the presence of the Referer header is not\nreliable enough under HTTP.)</p></li>\n</ol>\n<p>This ensures that only forms that have originated from your Web site can be used\nto 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/rfc2616.html\"><strong>RFC 2616</strong></a>). These requests ought never to have any potentially\ndangerous side effects , and so a CSRF attack with a GET request ought to be\nharmless. <span class=\"target\" id=\"index-2\"></span><a class=\"rfc reference external\" href=\"https://datatracker.ietf.org/doc/html/rfc2616.html\"><strong>RFC 2616</strong></a> defines POST, PUT and DELETE as ‘unsafe’, and all other\nmethods are assumed to be unsafe, for maximum protection.</p>\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/1.8/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\">csrf_token</code></a> template tag is used by a template (or the\n<code class=\"docutils literal notranslate\">get_token</code> function is called some other way), <code class=\"docutils literal notranslate\">CsrfViewMiddleware</code> will\nadd a cookie and a <code class=\"docutils literal notranslate\">Vary: Cookie</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\">UpdateCacheMiddleware</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\">django.views.decorators.csrf.csrf_protect()</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=\"nn\">django.views.decorators.cache</span> <span class=\"kn\">import</span> cache_page\n<span class=\"kn\">from</span> <span class=\"nn\">django.views.decorators.csrf</span> <span class=\"kn\">import</span> csrf_protect\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=\"nf\">my_view</span><span class=\"p\">(</span>request<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/1.8/topics/class-based-views/intro/#id2\"><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\">CsrfViewMiddleware</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\">csrf_protect</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=\"nn\">django.test</span> <span class=\"kn\">import</span> Client\n<span class=\"gp\">&gt;&gt;&gt; </span>csrf_client <span class=\"o\">=</span> Client<span class=\"p\">(</span>enforce_csrf_checks<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/1.8/topics/class-based-views/intro/#id2\"><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\">csrf_exempt</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">view</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=\"nn\">django.views.decorators.csrf</span> <span class=\"kn\">import</span> csrf_exempt\n<span class=\"kn\">from</span> <span class=\"nn\">django.http</span> <span class=\"kn\">import</span> HttpResponse\n\n<span class=\"nd\">@csrf_exempt</span>\n<span class=\"k\">def</span> <span class=\"nf\">my_view</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n    <span class=\"k\">return</span> HttpResponse<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\">requires_csrf_token</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">view</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/1.8/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\">csrf_token</code></a> template tag will not work if\n<code class=\"docutils literal notranslate\">CsrfViewMiddleware.process_view</code> or an equivalent like <code class=\"docutils literal notranslate\">csrf_protect</code>\nhas not run. The view decorator <code class=\"docutils literal notranslate\">requires_csrf_token</code> can be used to\nensure the template tag does work. This decorator works similarly to\n<code class=\"docutils literal notranslate\">csrf_protect</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=\"nn\">django.views.decorators.csrf</span> <span class=\"kn\">import</span> requires_csrf_token\n<span class=\"kn\">from</span> <span class=\"nn\">django.shortcuts</span> <span class=\"kn\">import</span> render\n\n<span class=\"nd\">@requires_csrf_token</span>\n<span class=\"k\">def</span> <span class=\"nf\">my_view</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n    c <span class=\"o\">=</span> <span class=\"p\">{}</span>\n    <span class=\"c1\"># ...</span>\n    <span class=\"k\">return</span> render<span class=\"p\">(</span>request<span class=\"p\">,</span> <span class=\"s2\">&quot;a_template.html&quot;</span><span class=\"p\">,</span> c<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\">ensure_csrf_cookie</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">view</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\">csrf_protect</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\">csrf_exempt()</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\">CsrfViewMiddleware.process_view</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\">requires_csrf_token()</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\">csrf_exempt</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\">csrf_exempt()</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\">requires_csrf_token()</code></a>. (i.e. <code class=\"docutils literal notranslate\">requires_csrf_token</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\">csrf_exempt()</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\">csrf_protect()</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=\"nn\">django.views.decorators.csrf</span> <span class=\"kn\">import</span> csrf_exempt<span class=\"p\">,</span> csrf_protect\n\n<span class=\"nd\">@csrf_exempt</span>\n<span class=\"k\">def</span> <span class=\"nf\">my_view</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n\n    <span class=\"nd\">@csrf_protect</span>\n    <span class=\"k\">def</span> <span class=\"nf\">protected_path</span><span class=\"p\">(</span>request<span class=\"p\">):</span>\n        do_something<span class=\"p\">()</span>\n\n    <span class=\"k\">if</span> some_condition<span class=\"p\">():</span>\n       <span class=\"k\">return</span> protected_path<span class=\"p\">(</span>request<span class=\"p\">)</span>\n    <span class=\"k\">else</span><span class=\"p\">:</span>\n       do_something_else<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/1.8/ref/templates/builtins/#std-templatetag-csrf_token\"><code class=\"xref std std-ttag docutils literal notranslate\">csrf_token</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\">ensure_csrf_cookie()</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\">CsrfViewMiddleware</code>,\nall relevant views in contrib apps use the <code class=\"docutils literal notranslate\">csrf_protect</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\">csrf_protect</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/1.8/ref/settings/#std-setting-CSRF_COOKIE_AGE\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_AGE</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_COOKIE_DOMAIN\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_DOMAIN</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_COOKIE_HTTPONLY\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_HTTPONLY</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_COOKIE_NAME\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_NAME</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_COOKIE_PATH\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_PATH</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_COOKIE_SECURE\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_COOKIE_SECURE</code></a></p></li>\n<li><p><a class=\"reference internal\" href=\"/en/1.8/ref/settings/#std-setting-CSRF_FAILURE_VIEW\"><code class=\"xref std std-setting docutils literal notranslate\">CSRF_FAILURE_VIEW</code></a></p></li>\n</ul>\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":"Other template engines","anchor":"other-template-engines","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":[]}],"breadcrumbs":[{"docname":"ref/index","title":"API Reference","url":"/en/1.8/ref/"}],"prev":{"docname":"ref/contrib/webdesign","title":"django.contrib.webdesign","url":"/en/1.8/ref/contrib/webdesign/"},"next":{"docname":"ref/databases","title":"Databases","url":"/en/1.8/ref/databases/"},"formats":{"html":"/en/1.8/ref/csrf/","markdown":"/en/1.8/ref/csrf.md","json":"/en/1.8/ref/csrf.json"},"source":"https://github.com/django/django/blob/stable/1.8.x/docs/ref/csrf.txt","official":"https://docs.djangoproject.com/en/1.8/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"]}