<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Cross Site Request Forgery protection — Django 1.11.20 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="Databases" href="databases.html" /> <link rel="prev" title="The syndication feed framework" href="contrib/syndication.html" /> <script type="text/javascript" src="../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head><body> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../index.html">Django 1.11.20 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../index.html">Home</a> | <a title="Table of contents" href="../contents.html">Table of contents</a> | <a title="Global index" href="../genindex.html">Index</a> | <a title="Module index" href="../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="contrib/syndication.html" title="The syndication feed framework">previous</a> | <a href="index.html" title="API Reference" accesskey="U">up</a> | <a href="databases.html" title="Databases">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="ref-csrf"> <div class="section" id="s-module-django.middleware.csrf"> <span id="s-cross-site-request-forgery-protection"></span><span id="module-django.middleware.csrf"></span><span id="cross-site-request-forgery-protection"></span><h1>Cross Site Request Forgery protection<a class="headerlink" href="#module-django.middleware.csrf" title="Permalink to this headline">¶</a></h1> <p>The CSRF middleware and template tag provides easy-to-use protection against <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 website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, ‘login CSRF’, where an attacking site tricks a user’s browser into logging into a site with someone else’s credentials, is also covered.</p> <p>The first defense against CSRF attacks is to ensure that GET requests (and other ‘safe’ methods, as defined by <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html#section-4.2.1"><strong>RFC 7231#section-4.2.1</strong></a>) are side effect free. Requests via ‘unsafe’ methods, such as POST, PUT, and DELETE, can then be protected by following the steps below.</p> <div class="section" id="s-how-to-use-it"> <span id="s-using-csrf"></span><span id="how-to-use-it"></span><span id="using-csrf"></span><h2>How to use it<a class="headerlink" href="#how-to-use-it" title="Permalink to this headline">¶</a></h2> <p>To take advantage of CSRF protection in your views, follow these steps:</p> <ol class="arabic"> <li><p class="first">The CSRF middleware is activated by default in the <a class="reference internal" href="settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> setting. If you override that setting, remember that <code class="docutils literal notranslate"><span class="pre">'django.middleware.csrf.CsrfViewMiddleware'</span></code> should come before any view middleware that assume that CSRF attacks have been dealt with.</p> <p>If you disabled it, which is not recommended, you can use <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 you want to protect (see below).</p> </li> <li><p class="first">In any template that uses a POST form, use the <a class="reference internal" href="templates/builtins.html#std:templatetag-csrf_token"><code class="xref std std-ttag docutils literal notranslate"><span class="pre">csrf_token</span></code></a> tag inside the <code class="docutils literal notranslate"><span class="pre"><form></span></code> element if the form is for an internal URL, e.g.:</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="p"><</span><span class="nt">form</span> <span class="na">action</span><span class="o">=</span><span class="s">""</span> <span class="na">method</span><span class="o">=</span><span class="s">"post"</span><span class="p">></span><span class="cp">{%</span> <span class="k">csrf_token</span> <span class="cp">%}</span> </pre></div> </div> <p>This should not be done for POST forms that target external URLs, since that would cause the CSRF token to be leaked, leading to a vulnerability.</p> </li> <li><p class="first">In the corresponding view functions, ensure that <a class="reference internal" href="templates/api.html#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 that <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 <a class="reference internal" href="../topics/http/shortcuts.html#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, you are covered already since these all use <code class="docutils literal notranslate"><span class="pre">RequestContext</span></code>.</p> </li> </ol> <div class="section" id="s-ajax"> <span id="s-csrf-ajax"></span><span id="ajax"></span><span id="csrf-ajax"></span><h3>AJAX<a class="headerlink" href="#ajax" title="Permalink to this headline">¶</a></h3> <p>While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom <code class="docutils literal notranslate"><span class="pre">X-CSRFToken</span></code> header to the value of the CSRF token. This is often easier, because many JavaScript frameworks provide hooks that allow headers to be set on every request.</p> <p>First, you must get the CSRF token. How to do that depends on whether or not the <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a> setting is enabled.</p> <div class="section" id="s-acquiring-the-token-if-csrf-use-sessions-is-false"> <span id="acquiring-the-token-if-csrf-use-sessions-is-false"></span><h4>Acquiring the token if <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a> is <code class="docutils literal notranslate"><span class="pre">False</span></code><a class="headerlink" href="#acquiring-the-token-if-csrf-use-sessions-is-false" title="Permalink to this headline">¶</a></h4> <p>The recommended source for the token is the <code class="docutils literal notranslate"><span class="pre">csrftoken</span></code> cookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p>The CSRF token cookie is named <code class="docutils literal notranslate"><span class="pre">csrftoken</span></code> by default, but you can control the cookie name via the <a class="reference internal" href="settings.html#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> <p class="last">The CSRF header name is <code class="docutils literal notranslate"><span class="pre">HTTP_X_CSRFTOKEN</span></code> by default, but you can customize it using the <a class="reference internal" href="settings.html#std:setting-CSRF_HEADER_NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_HEADER_NAME</span></code></a> setting.</p> </div> <p>Acquiring the token is straightforward:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="c1">// using jQuery</span> <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> <span class="kd">var</span> <span class="nx">cookieValue</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span> <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">&&</span> <span class="nb">document</span><span class="p">.</span><span class="nx">cookie</span> <span class="o">!==</span> <span class="s1">''</span><span class="p">)</span> <span class="p">{</span> <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">';'</span><span class="p">);</span> <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="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o"><</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> <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> <span class="c1">// Does this cookie string begin with the name we want?</span> <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="mi">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="mi">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">'='</span><span class="p">))</span> <span class="p">{</span> <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="mi">1</span><span class="p">));</span> <span class="k">break</span><span class="p">;</span> <span class="p">}</span> <span class="p">}</span> <span class="p">}</span> <span class="k">return</span> <span class="nx">cookieValue</span><span class="p">;</span> <span class="p">}</span> <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">'csrftoken'</span><span class="p">);</span> </pre></div> </div> <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> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><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">'csrftoken'</span><span class="p">);</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The CSRF token is also present in the DOM, but only if explicitly included using <a class="reference internal" href="templates/builtins.html#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 token; the <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code> will prefer the cookie to the token in the DOM. Regardless, you’re guaranteed to have the cookie if the token is present in the DOM, so you should use the cookie!</p> </div> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">If your view is not rendering a template containing the <a class="reference internal" href="templates/builtins.html#std:templatetag-csrf_token"><code class="xref std std-ttag docutils literal notranslate"><span class="pre">csrf_token</span></code></a> template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: <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> </div> </div> <div class="section" id="s-acquiring-the-token-if-csrf-use-sessions-is-true"> <span id="acquiring-the-token-if-csrf-use-sessions-is-true"></span><h4>Acquiring the token if <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code><a class="headerlink" href="#acquiring-the-token-if-csrf-use-sessions-is-true" title="Permalink to this headline">¶</a></h4> <p>If you activate <a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a>, you must include the CSRF token in your HTML and read the token from the DOM with JavaScript:</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">csrf_token</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">script</span> <span class="na">type</span><span class="o">=</span><span class="s">"text/javascript"</span><span class="p">></span> <span class="c1">// using jQuery</span> <span class="kd">var</span> <span class="nx">csrftoken</span> <span class="o">=</span> <span class="nx">jQuery</span><span class="p">(</span><span class="s2">"[name=csrfmiddlewaretoken]"</span><span class="p">).</span><span class="nx">val</span><span class="p">();</span> <span class="p"></</span><span class="nt">script</span><span class="p">></span> </pre></div> </div> </div> <div class="section" id="s-setting-the-token-on-the-ajax-request"> <span id="setting-the-token-on-the-ajax-request"></span><h4>Setting the token on the AJAX request<a class="headerlink" href="#setting-the-token-on-the-ajax-request" title="Permalink to this headline">¶</a></h4> <p>Finally, you’ll have to actually set the header on your AJAX request, while protecting the CSRF token from being sent to other domains using <a class="reference external" href="https://api.jquery.com/jQuery.ajax/">settings.crossDomain</a> in jQuery 1.5.1 and newer:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><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> <span class="c1">// these HTTP methods do not require CSRF protection</span> <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> <span class="p">}</span> <span class="nx">$</span><span class="p">.</span><span class="nx">ajaxSetup</span><span class="p">({</span> <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> <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">&&</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> <span class="nx">xhr</span><span class="p">.</span><span class="nx">setRequestHeader</span><span class="p">(</span><span class="s2">"X-CSRFToken"</span><span class="p">,</span> <span class="nx">csrftoken</span><span class="p">);</span> <span class="p">}</span> <span class="p">}</span> <span class="p">});</span> </pre></div> </div> <p>If you’re using AngularJS 1.1.3 and newer, it’s sufficient to configure the <code class="docutils literal notranslate"><span class="pre">$http</span></code> provider with the cookie and header names:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="nx">$httpProvider</span><span class="p">.</span><span class="nx">defaults</span><span class="p">.</span><span class="nx">xsrfCookieName</span> <span class="o">=</span> <span class="s1">'csrftoken'</span><span class="p">;</span> <span class="nx">$httpProvider</span><span class="p">.</span><span class="nx">defaults</span><span class="p">.</span><span class="nx">xsrfHeaderName</span> <span class="o">=</span> <span class="s1">'X-CSRFToken'</span><span class="p">;</span> </pre></div> </div> </div> </div> <div class="section" id="s-using-csrf-in-jinja2-templates"> <span id="using-csrf-in-jinja2-templates"></span><h3>Using CSRF in Jinja2 templates<a class="headerlink" href="#using-csrf-in-jinja2-templates" title="Permalink to this headline">¶</a></h3> <p>Django’s <a class="reference internal" href="../topics/templates.html#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 adds <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 to <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> <div class="highlight-html+jinja notranslate"><div class="highlight"><pre><span></span><span class="p"><</span><span class="nt">form</span> <span class="na">action</span><span class="o">=</span><span class="s">""</span> <span class="na">method</span><span class="o">=</span><span class="s">"post"</span><span class="p">></span><span class="cp">{{</span> <span class="nv">csrf_input</span> <span class="cp">}}</span> </pre></div> </div> </div> <div class="section" id="s-module-django.views.decorators.csrf"> <span id="s-the-decorator-method"></span><span id="module-django.views.decorators.csrf"></span><span id="the-decorator-method"></span><h3>The decorator method<a class="headerlink" href="#module-django.views.decorators.csrf" title="Permalink to this headline">¶</a></h3> <p>Rather than adding <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code> as a blanket protection, you can use the <code class="docutils literal notranslate"><span class="pre">csrf_protect</span></code> decorator, which has exactly the same functionality, on particular views that need the protection. It must be used <strong>both</strong> on views that insert the CSRF token in the output, and on those that accept the POST form data. (These are often the same view function, but not always).</p> <p>Use of the decorator by itself is <strong>not recommended</strong>, since if you forget to use it, you will have a security hole. The ‘belt and braces’ strategy of using both is fine, and will incur minimal overhead.</p> <dl class="function"> <dt id="django.views.decorators.csrf.csrf_protect"> <code class="descname">csrf_protect</code>(<em>view</em>)<a class="headerlink" href="#django.views.decorators.csrf.csrf_protect" title="Permalink to this definition">¶</a></dt> <dd><p>Decorator that provides the protection of <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code> to a view.</p> <p>Usage:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.csrf</span> <span class="k">import</span> <span class="n">csrf_protect</span> <span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">render</span> <span class="nd">@csrf_protect</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">c</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># ...</span> <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">"a_template.html"</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> </pre></div> </div> <p>If you are using class-based views, you can refer to <a class="reference internal" href="../topics/class-based-views/intro.html#id1"><span class="std std-ref">Decorating class-based views</span></a>.</p> </dd></dl> </div> </div> <div class="section" id="s-rejected-requests"> <span id="s-csrf-rejected-requests"></span><span id="rejected-requests"></span><span id="csrf-rejected-requests"></span><h2>Rejected requests<a class="headerlink" href="#rejected-requests" title="Permalink to this headline">¶</a></h2> <p>By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code>. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.</p> <p>The error page, however, is not very friendly, so you may want to provide your own view for handling this condition. To do this, simply set the <a class="reference internal" href="settings.html#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> <p>CSRF failures are logged as warnings to the <a class="reference internal" href="../topics/logging.html#django-security-logger"><span class="std std-ref">django.security.csrf</span></a> logger.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.11:</span> <p>In older versions, CSRF failures are logged to the <code class="docutils literal notranslate"><span class="pre">django.request</span></code> logger.</p> </div> </div> <div class="section" id="s-how-it-works"> <span id="s-how-csrf-works"></span><span id="how-it-works"></span><span id="how-csrf-works"></span><h2>How it works<a class="headerlink" href="#how-it-works" title="Permalink to this headline">¶</a></h2> <p>The CSRF protection is based on the following things:</p> <ol class="arabic"> <li><p class="first">A CSRF cookie that is based on a random secret value, which other sites will not have access to.</p> <p>This cookie is set by <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code>. It is sent with every response that has called <code class="docutils literal notranslate"><span class="pre">django.middleware.csrf.get_token()</span></code> (the function used internally to retrieve the CSRF token), if it wasn’t already set on the request.</p> <p>In order to protect against <a class="reference external" href="http://breachattack.com/">BREACH</a> attacks, the token is not simply the secret; a random salt is prepended to the secret and used to scramble it.</p> <p>For security reasons, the value of the secret is changed each time a user logs in.</p> </li> <li><p class="first">A hidden form field with the name ‘csrfmiddlewaretoken’ present in all outgoing POST forms. The value of this field is, again, the value of the secret, with a salt which is both added to it and used to scramble it. The salt is regenerated on every call to <code class="docutils literal notranslate"><span class="pre">get_token()</span></code> so that the form field value is changed in every such response.</p> <p>This part is done by the template tag.</p> </li> <li><p class="first">For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the ‘csrfmiddlewaretoken’ field must be present and correct. If it isn’t, the user will get a 403 error.</p> <p>When validating the ‘csrfmiddlewaretoken’ field value, only the secret, not the full token, is compared with the secret in the cookie value. This allows the use of ever-changing tokens. While each request may use its own token, the secret remains common to all.</p> <p>This check is done by <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code>.</p> </li> <li><p class="first">In addition, for HTTPS requests, strict referer checking is done by <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code>. This means that even if a subdomain can set or modify cookies on your domain, it can’t force a user to post to your application since that request won’t come from your own exact domain.</p> <p>This also addresses a man-in-the-middle attack that’s possible under HTTPS when using a session independent secret, due to the fact that HTTP <code class="docutils literal notranslate"><span class="pre">Set-Cookie</span></code> headers are (unfortunately) accepted by clients even when they are talking to a site under HTTPS. (Referer checking is not done for HTTP requests because the presence of the <code class="docutils literal notranslate"><span class="pre">Referer</span></code> header isn’t reliable enough under HTTP.)</p> <p>If the <a class="reference internal" href="settings.html#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 against it. This setting supports subdomains. 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 requests 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 not set, then the referer must match the HTTP <code class="docutils literal notranslate"><span class="pre">Host</span></code> header.</p> <p>Expanding the accepted referers beyond the current host or cookie domain can be done with the <a class="reference internal" href="settings.html#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> </li> </ol> <p>This ensures that only forms that have originated from trusted domains can be used to POST data back.</p> <p>It deliberately ignores GET requests (and other requests that are defined as ‘safe’ by <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html"><strong>RFC 7231</strong></a>). These requests ought never to have any potentially dangerous side effects , and so a CSRF attack with a GET request ought to be harmless. <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html"><strong>RFC 7231</strong></a> defines POST, PUT, and DELETE as ‘unsafe’, and all other methods are also assumed to be unsafe, for maximum protection.</p> <p>The CSRF protection cannot protect against man-in-the-middle attacks, so use <a class="reference internal" href="../topics/security.html#security-recommendation-ssl"><span class="std std-ref">HTTPS</span></a> with <a class="reference internal" href="middleware.html#http-strict-transport-security"><span class="std std-ref">HTTP Strict Transport Security</span></a>. It also assumes <a class="reference internal" href="../topics/security.html#host-headers-virtual-hosting"><span class="std std-ref">validation of the HOST header</span></a> and that there aren’t any <a class="reference internal" href="../topics/security.html#cross-site-scripting"><span class="std std-ref">cross-site scripting vulnerabilities</span></a> on your site (because XSS vulnerabilities already let an attacker do anything a CSRF vulnerability allows and much worse).</p> <div class="versionchanged"> <span class="title">Changed in Django 1.10:</span> <p>Added salting to the token and started changing it with each request to protect against <a class="reference external" href="http://breachattack.com/">BREACH</a> attacks.</p> </div> </div> <div class="section" id="s-caching"> <span id="caching"></span><h2>Caching<a class="headerlink" href="#caching" title="Permalink to this headline">¶</a></h2> <p>If the <a class="reference internal" href="templates/builtins.html#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 <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 add 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 middleware will play well with the cache middleware if it is used as instructed (<code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> goes before all other middleware).</p> <p>However, if you use cache decorators on individual views, the CSRF middleware will not yet have been able to set the Vary header or the CSRF cookie, and the response will be cached without either one. In this case, on any views that will require a CSRF token to be inserted you should use the <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> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="k">import</span> <span class="n">cache_page</span> <span class="kn">from</span> <span class="nn">django.views.decorators.csrf</span> <span class="k">import</span> <span class="n">csrf_protect</span> <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> <span class="nd">@csrf_protect</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>If you are using class-based views, you can refer to <a class="reference internal" href="../topics/class-based-views/intro.html#id1"><span class="std std-ref">Decorating class-based views</span></a>.</p> </div> <div class="section" id="s-testing"> <span id="testing"></span><h2>Testing<a class="headerlink" href="#testing" title="Permalink to this headline">¶</a></h2> <p>The <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code> will usually be a big hindrance to testing view functions, due to the need for the CSRF token which must be sent with every POST request. For this reason, Django’s HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the <code class="docutils literal notranslate"><span class="pre">csrf_protect</span></code> decorator so that they no longer rejects requests. In every other respect (e.g. sending cookies etc.), they behave the same.</p> <p>If, for some reason, you <em>want</em> the test client to perform CSRF checks, you can create an instance of the test client that enforces CSRF checks:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.test</span> <span class="k">import</span> <span class="n">Client</span> <span class="gp">>>> </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> </pre></div> </div> </div> <div class="section" id="s-limitations"> <span id="s-csrf-limitations"></span><span id="limitations"></span><span id="csrf-limitations"></span><h2>Limitations<a class="headerlink" href="#limitations" title="Permalink to this headline">¶</a></h2> <p>Subdomains within a site will be able to set cookies on the client for the whole domain. By setting the cookie and using a corresponding token, subdomains will be able to circumvent the CSRF protection. The only way to avoid this is to ensure that subdomains are controlled by trusted users (or, are at least unable to set cookies). Note that even without CSRF, there are other vulnerabilities, such as session fixation, that make giving subdomains to untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed with current browsers.</p> </div> <div class="section" id="s-edge-cases"> <span id="edge-cases"></span><h2>Edge cases<a class="headerlink" href="#edge-cases" title="Permalink to this headline">¶</a></h2> <p>Certain views can have unusual requirements that mean they don’t fit the normal pattern envisaged here. A number of utilities can be useful in these situations. The scenarios they might be needed in are described in the following section.</p> <div class="section" id="s-utilities"> <span id="utilities"></span><h3>Utilities<a class="headerlink" href="#utilities" title="Permalink to this headline">¶</a></h3> <p>The examples below assume you are using function-based views. If you are working with class-based views, you can refer to <a class="reference internal" href="../topics/class-based-views/intro.html#id1"><span class="std std-ref">Decorating class-based views</span></a>.</p> <dl class="function"> <dt id="django.views.decorators.csrf.csrf_exempt"> <code class="descname">csrf_exempt</code>(<em>view</em>)<a class="reference internal" href="../_modules/django/views/decorators/csrf.html#csrf_exempt"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.views.decorators.csrf.csrf_exempt" title="Permalink to this definition">¶</a></dt> <dd><p>This decorator marks a view as being exempt from the protection ensured by the middleware. Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.csrf</span> <span class="k">import</span> <span class="n">csrf_exempt</span> <span class="kn">from</span> <span class="nn">django.http</span> <span class="k">import</span> <span class="n">HttpResponse</span> <span class="nd">@csrf_exempt</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s1">'Hello world'</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="function"> <dt id="django.views.decorators.csrf.requires_csrf_token"> <code class="descname">requires_csrf_token</code>(<em>view</em>)<a class="headerlink" href="#django.views.decorators.csrf.requires_csrf_token" title="Permalink to this definition">¶</a></dt> <dd><p>Normally the <a class="reference internal" href="templates/builtins.html#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 <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> has not run. The view decorator <code class="docutils literal notranslate"><span class="pre">requires_csrf_token</span></code> can be used to ensure the template tag does work. This decorator works similarly to <code class="docutils literal notranslate"><span class="pre">csrf_protect</span></code>, but never rejects an incoming request.</p> <p>Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.csrf</span> <span class="k">import</span> <span class="n">requires_csrf_token</span> <span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">render</span> <span class="nd">@requires_csrf_token</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">c</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># ...</span> <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">"a_template.html"</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="function"> <dt id="django.views.decorators.csrf.ensure_csrf_cookie"> <code class="descname">ensure_csrf_cookie</code>(<em>view</em>)<a class="headerlink" href="#django.views.decorators.csrf.ensure_csrf_cookie" title="Permalink to this definition">¶</a></dt> <dd><p>This decorator forces a view to send the CSRF cookie.</p> </dd></dl> </div> <div class="section" id="s-scenarios"> <span id="scenarios"></span><h3>Scenarios<a class="headerlink" href="#scenarios" title="Permalink to this headline">¶</a></h3> <div class="section" id="s-csrf-protection-should-be-disabled-for-just-a-few-views"> <span id="csrf-protection-should-be-disabled-for-just-a-few-views"></span><h4>CSRF protection should be disabled for just a few views<a class="headerlink" href="#csrf-protection-should-be-disabled-for-just-a-few-views" title="Permalink to this headline">¶</a></h4> <p>Most views requires CSRF protection, but a few do not.</p> <p>Solution: rather than disabling the middleware and applying <code class="docutils literal notranslate"><span class="pre">csrf_protect</span></code> to all the views that need it, enable the middleware and 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>.</p> </div> <div class="section" id="s-csrfviewmiddleware-process-view-not-used"> <span id="csrfviewmiddleware-process-view-not-used"></span><h4>CsrfViewMiddleware.process_view not used<a class="headerlink" href="#csrfviewmiddleware-process-view-not-used" title="Permalink to this headline">¶</a></h4> <p>There are cases when <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware.process_view</span></code> may not have run before your view is run - 404 and 500 handlers, for example - but you still need the CSRF token in a form.</p> <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> </div> <div class="section" id="s-unprotected-view-needs-the-csrf-token"> <span id="unprotected-view-needs-the-csrf-token"></span><h4>Unprotected view needs the CSRF token<a class="headerlink" href="#unprotected-view-needs-the-csrf-token" title="Permalink to this headline">¶</a></h4> <p>There may be some views that are unprotected and have been exempted by <code class="docutils literal notranslate"><span class="pre">csrf_exempt</span></code>, but still need to include the CSRF token.</p> <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 <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> should be the innermost decorator).</p> </div> <div class="section" id="s-view-needs-protection-for-one-path"> <span id="view-needs-protection-for-one-path"></span><h4>View needs protection for one path<a class="headerlink" href="#view-needs-protection-for-one-path" title="Permalink to this headline">¶</a></h4> <p>A view needs CSRF protection under one set of conditions only, and mustn’t have it for the rest of the time.</p> <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 view 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 path within it that needs protection. Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.csrf</span> <span class="k">import</span> <span class="n">csrf_exempt</span><span class="p">,</span> <span class="n">csrf_protect</span> <span class="nd">@csrf_exempt</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="nd">@csrf_protect</span> <span class="k">def</span> <span class="nf">protected_path</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">do_something</span><span class="p">()</span> <span class="k">if</span> <span class="n">some_condition</span><span class="p">():</span> <span class="k">return</span> <span class="n">protected_path</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">do_something_else</span><span class="p">()</span> </pre></div> </div> </div> <div class="section" id="s-page-uses-ajax-without-any-html-form"> <span id="page-uses-ajax-without-any-html-form"></span><h4>Page uses AJAX without any HTML form<a class="headerlink" href="#page-uses-ajax-without-any-html-form" title="Permalink to this headline">¶</a></h4> <p>A page makes a POST request via AJAX, and the page does not have an HTML form with a <a class="reference internal" href="templates/builtins.html#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> <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 view that sends the page.</p> </div> </div> </div> <div class="section" id="s-contrib-and-reusable-apps"> <span id="contrib-and-reusable-apps"></span><h2>Contrib and reusable apps<a class="headerlink" href="#contrib-and-reusable-apps" title="Permalink to this headline">¶</a></h2> <p>Because it is possible for the developer to turn off the <code class="docutils literal notranslate"><span class="pre">CsrfViewMiddleware</span></code>, all relevant views in contrib apps use the <code class="docutils literal notranslate"><span class="pre">csrf_protect</span></code> decorator to ensure the security of these applications against CSRF. It is recommended that the developers of other reusable apps that want the same guarantees also use the <code class="docutils literal notranslate"><span class="pre">csrf_protect</span></code> decorator on their views.</p> </div> <div class="section" id="s-settings"> <span id="settings"></span><h2>Settings<a class="headerlink" href="#settings" title="Permalink to this headline">¶</a></h2> <p>A number of settings can be used to control Django’s CSRF behavior:</p> <ul class="simple"> <li><a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_AGE</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_DOMAIN"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_DOMAIN</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_HTTPONLY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_HTTPONLY</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_NAME</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_PATH"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_PATH</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_SECURE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_SECURE</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_FAILURE_VIEW"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_FAILURE_VIEW</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_HEADER_NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_HEADER_NAME</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_TRUSTED_ORIGINS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_TRUSTED_ORIGINS</span></code></a></li> <li><a class="reference internal" href="settings.html#std:setting-CSRF_USE_SESSIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code></a></li> </ul> </div> <div class="section" id="s-frequently-asked-questions"> <span id="frequently-asked-questions"></span><h2>Frequently Asked Questions<a class="headerlink" href="#frequently-asked-questions" title="Permalink to this headline">¶</a></h2> <div class="section" id="s-is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability"> <span id="is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability"></span><h3>Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?<a class="headerlink" href="#is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability" title="Permalink to this headline">¶</a></h3> <p>No, this is by design. Without a man-in-the-middle attack, there is no way for an attacker to send a CSRF token cookie to a victim’s browser, so a successful attack would need to obtain the victim’s browser’s cookie via XSS or similar, in which case an attacker usually doesn’t need CSRF attacks.</p> <p>Some security audit tools flag this as a problem but as mentioned before, an attacker cannot steal a user’s browser’s CSRF cookie. “Stealing” or modifying <em>your own</em> token using Firebug, Chrome dev tools, etc. isn’t a vulnerability.</p> </div> <div class="section" id="s-is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default"> <span id="is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default"></span><h3>Is it a problem that Django’s CSRF protection isn’t linked to a session by default?<a class="headerlink" href="#is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default" title="Permalink to this headline">¶</a></h3> <p>No, this is by design. Not linking CSRF protection to a session allows using the protection on sites such as a <cite>pastebin</cite> that allow submissions from anonymous users which don’t have a session.</p> <p>If you wish to store the CSRF token in the user’s session, use the <a class="reference internal" href="settings.html#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> </div> <div class="section" id="s-why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in"> <span id="why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in"></span><h3>Why might a user encounter a CSRF validation failure after logging in?<a class="headerlink" href="#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in" title="Permalink to this headline">¶</a></h3> <p>For security reasons, CSRF tokens are rotated each time a user logs in. Any page with a form generated before a login will have an old, invalid CSRF token and need to be reloaded. This might happen if a user uses the back button after a login or if they log in in a different browser tab.</p> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Cross Site Request Forgery protection</a><ul> <li><a class="reference internal" href="#how-to-use-it">How to use it</a><ul> <li><a class="reference internal" href="#ajax">AJAX</a><ul> <li><a class="reference internal" href="#acquiring-the-token-if-csrf-use-sessions-is-false">Acquiring the token if <code class="docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code></a></li> <li><a class="reference internal" href="#acquiring-the-token-if-csrf-use-sessions-is-true">Acquiring the token if <code class="docutils literal notranslate"><span class="pre">CSRF_USE_SESSIONS</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code></a></li> <li><a class="reference internal" href="#setting-the-token-on-the-ajax-request">Setting the token on the AJAX request</a></li> </ul> </li> <li><a class="reference internal" href="#using-csrf-in-jinja2-templates">Using CSRF in Jinja2 templates</a></li> <li><a class="reference internal" href="#module-django.views.decorators.csrf">The decorator method</a></li> </ul> </li> <li><a class="reference internal" href="#rejected-requests">Rejected requests</a></li> <li><a class="reference internal" href="#how-it-works">How it works</a></li> <li><a class="reference internal" href="#caching">Caching</a></li> <li><a class="reference internal" href="#testing">Testing</a></li> <li><a class="reference internal" href="#limitations">Limitations</a></li> <li><a class="reference internal" href="#edge-cases">Edge cases</a><ul> <li><a class="reference internal" href="#utilities">Utilities</a></li> <li><a class="reference internal" href="#scenarios">Scenarios</a><ul> <li><a class="reference internal" href="#csrf-protection-should-be-disabled-for-just-a-few-views">CSRF protection should be disabled for just a few views</a></li> <li><a class="reference internal" href="#csrfviewmiddleware-process-view-not-used">CsrfViewMiddleware.process_view not used</a></li> <li><a class="reference internal" href="#unprotected-view-needs-the-csrf-token">Unprotected view needs the CSRF token</a></li> <li><a class="reference internal" href="#view-needs-protection-for-one-path">View needs protection for one path</a></li> <li><a class="reference internal" href="#page-uses-ajax-without-any-html-form">Page uses AJAX without any HTML form</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#contrib-and-reusable-apps">Contrib and reusable apps</a></li> <li><a class="reference internal" href="#settings">Settings</a></li> <li><a class="reference internal" href="#frequently-asked-questions">Frequently Asked Questions</a><ul> <li><a class="reference internal" href="#is-posting-an-arbitrary-csrf-token-pair-cookie-and-post-data-a-vulnerability">Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?</a></li> <li><a class="reference internal" href="#is-it-a-problem-that-django-s-csrf-protection-isn-t-linked-to-a-session-by-default">Is it a problem that Django’s CSRF protection isn’t linked to a session by default?</a></li> <li><a class="reference internal" href="#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in">Why might a user encounter a CSRF validation failure after logging in?</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="contrib/syndication.html" title="previous chapter">The syndication feed framework</a></p> <h4>Next topic</h4> <p class="topless"><a href="databases.html" title="next chapter">Databases</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/ref/csrf.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Feb 11, 2019</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="contrib/syndication.html" title="The syndication feed framework">previous</a> | <a href="index.html" title="API Reference" accesskey="U">up</a> | <a href="databases.html" title="Databases">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>