Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 65530c6176058f9b54858c3b4f6385e6 > files > 750

python-django-doc-1.8.19-1.mga6.noarch.rpm

<!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="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Cross Site Request Forgery protection &#8212; Django 1.8.19 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">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.8.19',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </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>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="top" title="Django 1.8.19 documentation" href="../contents.html" />
    <link rel="up" title="API Reference" href="index.html" />
    <link rel="next" title="Databases" href="databases.html" />
    <link rel="prev" title="django.contrib.webdesign" href="contrib/webdesign.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 role="document">

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.8.19 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">
    &laquo; <a href="contrib/webdesign.html" title="django.contrib.webdesign">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="databases.html" title="Databases">next</a> &raquo;</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="http://www.squarefree.com/securitytips/web-developers.html#CSRF">Cross Site Request Forgeries</a>.  This type of attack occurs when a malicious
Web site contains a link, a form button or some JavaScript that is intended to
perform some action on your Web site, using the credentials of a logged-in user
who visits the malicious site in their browser.  A related type of attack,
&#8216;login CSRF&#8217;, where an attacking site tricks a user&#8217;s browser into logging into
a site with someone else&#8217;s credentials, is also covered.</p>
<p>The first defense against CSRF attacks is to ensure that GET requests (and other
&#8216;safe&#8217; methods, as defined by 9.1.1 Safe Methods, HTTP 1.1,
<span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html#section-9.1.1"><strong>RFC 2616#section-9.1.1</strong></a>) are side-effect free. Requests via &#8216;unsafe&#8217; 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_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a> setting. If you override that setting, remember
that <code class="docutils literal"><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"><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"><span class="pre">csrf_token</span></code></a> tag inside
the <code class="docutils literal"><span class="pre">&lt;form&gt;</span></code> element if the form is for an internal URL, e.g.:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">form</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;&quot;</span> <span class="n">method</span><span class="o">=</span><span class="s2">&quot;post&quot;</span><span class="o">&gt;</span><span class="p">{</span><span class="o">%</span> <span class="n">csrf_token</span> <span class="o">%</span><span class="p">}</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 the
<code class="docutils literal"><span class="pre">'django.template.context_processors.csrf'</span></code> context processor is
being used. Usually, this can be done in one of two ways:</p>
<ol class="arabic">
<li><p class="first">Use RequestContext, which always uses
<code class="docutils literal"><span class="pre">'django.template.context_processors.csrf'</span></code> (no matter what template
context processors are configured in the <a class="reference internal" href="settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal"><span class="pre">TEMPLATES</span></code></a> setting).
If you are using generic views or contrib apps, you are covered already,
since these apps use RequestContext throughout.</p>
</li>
<li><p class="first">Manually import and use the processor to generate the CSRF token and
add it to the template context. e.g.:</p>
<div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">render_to_response</span>
<span class="kn">from</span> <span class="nn">django.template.context_processors</span> <span class="k">import</span> <span class="n">csrf</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="n">c</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">csrf</span><span class="p">(</span><span class="n">request</span><span class="p">))</span>
    <span class="c1"># ... view code here</span>
    <span class="k">return</span> <span class="n">render_to_response</span><span class="p">(</span><span class="s2">&quot;a_template.html&quot;</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span>
</pre></div>
</div>
<p>You may want to write your own
<a class="reference internal" href="../topics/http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><code class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></code></a> wrapper that takes care
of this step for you.</p>
</li>
</ol>
</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"><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>As a first step, you must get the CSRF token itself. The recommended source for
the token is the <code class="docutils literal"><span class="pre">csrftoken</span></code> cookie, which will be set if you&#8217;ve enabled CSRF
protection for your views as outlined above.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The CSRF token cookie is named <code class="docutils literal"><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"><span class="pre">CSRF_COOKIE_NAME</span></code></a> setting.</p>
</div>
<p>Acquiring the token is straightforward:</p>
<div class="highlight-javascript"><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">&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>
        <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>
        <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">&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>
            <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">&#39;=&#39;</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">&#39;csrftoken&#39;</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"><span class="pre">getCookie</span></code>:</p>
<div class="highlight-javascript"><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">&#39;csrftoken&#39;</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"><span class="pre">csrf_token</span></code></a> in a template. The cookie contains the canonical
token; the <code class="docutils literal"><span class="pre">CsrfViewMiddleware</span></code> will prefer the cookie to the token in
the DOM. Regardless, you&#8217;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"><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"><span class="pre">ensure_csrf_cookie()</span></code></a>.</p>
</div>
<p>Finally, you&#8217;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="http://api.jquery.com/jQuery.ajax">settings.crossDomain</a> in jQuery 1.5.1 and
newer:</p>
<div class="highlight-javascript"><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">&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>
            <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>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">});</span>
</pre></div>
</div>
</div>
<div class="section" id="s-other-template-engines">
<span id="other-template-engines"></span><h3>Other template engines<a class="headerlink" href="#other-template-engines" title="Permalink to this headline">¶</a></h3>
<p>When using a different template engine than Django&#8217;s built-in engine, you can
set the token in your forms manually after making sure it&#8217;s available in the
template context.</p>
<p>For example, in the Jinja2 template language, your form could contain the
following:</p>
<div class="highlight-html"><div class="highlight"><pre><span></span><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>
    <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>
<span class="p">&lt;/</span><span class="nt">div</span><span class="p">&gt;</span>
</pre></div>
</div>
<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
the value of the CSRF token.</p>
</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"><span class="pre">CsrfViewMiddleware</span></code> as a blanket protection, you can use
the <code class="docutils literal"><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 &#8216;belt and braces&#8217; 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"><span class="pre">CsrfViewMiddleware</span></code> to a view.</p>
<p>Usage:</p>
<div class="highlight-default"><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">&quot;a_template.html&quot;</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#id2"><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="rejected-requests"></span><h2>Rejected requests<a class="headerlink" href="#rejected-requests" title="Permalink to this headline">¶</a></h2>
<p>By default, a &#8216;403 Forbidden&#8217; response is sent to the user if an incoming
request fails the checks performed by <code class="docutils literal"><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"><span class="pre">CSRF_FAILURE_VIEW</span></code></a> setting.</p>
</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 set to a random value (a session independent nonce, as
it is called), which other sites will not have access to.</p>
<p>This cookie is set by <code class="docutils literal"><span class="pre">CsrfViewMiddleware</span></code>.  It is meant to be permanent,
but since there is no way to set a cookie that never expires, it is sent with
every response that has called <code class="docutils literal"><span class="pre">django.middleware.csrf.get_token()</span></code>
(the function used internally to retrieve the CSRF token).</p>
</li>
<li><p class="first">A hidden form field with the name &#8216;csrfmiddlewaretoken&#8217; present in all
outgoing POST forms.  The value of this field is the value of the CSRF
cookie.</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 &#8216;csrfmiddlewaretoken&#8217; field
must be present and correct. If it isn&#8217;t, the user will get a 403 error.</p>
<p>This check is done by <code class="docutils literal"><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"><span class="pre">CsrfViewMiddleware</span></code>.  This is necessary to address a Man-In-The-Middle
attack that is possible under HTTPS when using a session independent nonce,
due to the fact that HTTP &#8216;Set-Cookie&#8217; headers are (unfortunately) accepted
by clients that are talking to a site under HTTPS.  (Referer checking is not
done for HTTP requests because the presence of the Referer header is not
reliable enough under HTTP.)</p>
</li>
</ol>
<p>This ensures that only forms that have originated from your Web site can be used
to POST data back.</p>
<p>It deliberately ignores GET requests (and other requests that are defined as
&#8216;safe&#8217; by <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</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/rfc2616.html"><strong>RFC 2616</strong></a> defines POST, PUT and DELETE as &#8216;unsafe&#8217;, and all other
methods are assumed to be unsafe, for maximum protection.</p>
</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"><span class="pre">csrf_token</span></code></a> template tag is used by a template (or the
<code class="docutils literal"><span class="pre">get_token</span></code> function is called some other way), <code class="docutils literal"><span class="pre">CsrfViewMiddleware</span></code> will
add a cookie and a <code class="docutils literal"><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"><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"><span class="pre">django.views.decorators.csrf.csrf_protect()</span></code></a> decorator first:</p>
<div class="highlight-default"><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#id2"><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"><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&#8217;s HTTP client for tests has been modified to
set a flag on requests which relaxes the middleware and the <code class="docutils literal"><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"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </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">&gt;&gt;&gt; </span><span class="n">csrf_client</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">enforce_csrf_checks</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</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&#8217;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#id2"><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="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"><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">&#39;Hello world&#39;</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"><span class="pre">csrf_token</span></code></a> template tag will not work if
<code class="docutils literal"><span class="pre">CsrfViewMiddleware.process_view</span></code> or an equivalent like <code class="docutils literal"><span class="pre">csrf_protect</span></code>
has not run. The view decorator <code class="docutils literal"><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"><span class="pre">csrf_protect</span></code>, but never rejects an incoming request.</p>
<p>Example:</p>
<div class="highlight-default"><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">&quot;a_template.html&quot;</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"><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"><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"><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"><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"><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"><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"><span class="pre">requires_csrf_token()</span></code></a>. (i.e. <code class="docutils literal"><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&#8217;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"><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"><span class="pre">csrf_protect()</span></code></a> for the
path within it that needs protection. Example:</p>
<div class="highlight-default"><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"><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"><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"><span class="pre">CsrfViewMiddleware</span></code>,
all relevant views in contrib apps use the <code class="docutils literal"><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"><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&#8217;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"><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"><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"><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"><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"><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"><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"><span class="pre">CSRF_FAILURE_VIEW</span></code></a></li>
</ul>
</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></li>
<li><a class="reference internal" href="#other-template-engines">Other template engines</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>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="contrib/webdesign.html">django.contrib.webdesign</a></li>
    
    
      <li>Next: <a href="databases.html">Databases</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.8.19 documentation</a>
        
          <ul><li><a href="index.html">API Reference</a>
        
        <ul><li>Cross Site Request Forgery protection</li></ul>
        </li></ul>
      </li>
  </ul>

  <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>
    <form class="search" action="../search.html" method="get">
      <div><input type="text" name="q" /></div>
      <div><input type="submit" value="Go" /></div>
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Mar 10, 2018</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="contrib/webdesign.html" title="django.contrib.webdesign">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="databases.html" title="Databases">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>