Sophie

Sophie

distrib > Mandriva > current > i586 > media > main-updates > by-pkgid > 57efe471f3561e70a829edf1b0e9f507 > files > 2296

python-django-1.1.4-0.1mdv2010.2.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">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Cross Site Request Forgery protection &mdash; Django v1.1 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.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django v1.1 documentation" href="../../index.html" />
    <link rel="up" title="contrib packages" href="index.html" />
    <link rel="next" title="Databrowse" href="databrowse.html" />
    <link rel="prev" title="The contenttypes framework" href="contenttypes.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 v1.1 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="../../modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="contenttypes.html" title="The contenttypes framework">previous</a> 
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="databrowse.html" title="Databrowse">next</a> &raquo;</div>
    </div>
    
    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-contrib-csrf">
            
  <div class="section" id="s-module-django.contrib.csrf">
<span id="s-ref-contrib-csrf"></span><span id="module-django.contrib.csrf"></span><span id="ref-contrib-csrf"></span><h1>Cross Site Request Forgery protection<a class="headerlink" href="#module-django.contrib.csrf" title="Permalink to this headline">¶</a></h1>
<p>The CsrfMiddleware class 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 creates a link or form button that is intended to perform some action
on your Web site, using the credentials of a logged-in user who is tricked
into clicking on the link in their browser.</p>
<p>The first defense against CSRF attacks is to ensure that GET requests
are side-effect free.  POST requests can then be protected by adding this
middleware into your list of installed middleware.</p>
<div class="section" id="s-how-to-use-it">
<span id="how-to-use-it"></span><h2>How to use it<a class="headerlink" href="#how-to-use-it" title="Permalink to this headline">¶</a></h2>
<p>Add the middleware <tt class="docutils literal"><span class="pre">'django.contrib.csrf.middleware.CsrfMiddleware'</span></tt> to your
list of middleware classes, <a class="reference external" href="../settings.html#setting-MIDDLEWARE_CLASSES"><tt class="xref docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></tt></a>. It needs to process
the response after the SessionMiddleware, so must come before it in the list. It
also must process the response before things like compression or setting of
ETags happen to the response, so it must come after GZipMiddleware,
CommonMiddleware and ConditionalGetMiddleware in the list.</p>
<p>The <tt class="docutils literal"><span class="pre">CsrfMiddleware</span></tt> class is actually composed of two middleware:
<tt class="docutils literal"><span class="pre">CsrfViewMiddleware</span></tt> which performs the checks on incoming requests,
and <tt class="docutils literal"><span class="pre">CsrfResponseMiddleware</span></tt> which performs post-processing of the
result.  This allows the individual components to be used and/or
replaced instead of using <tt class="docutils literal"><span class="pre">CsrfMiddleware</span></tt>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.1:</span> (previous versions of Django did not provide these two components
of <tt class="docutils literal"><span class="pre">CsrfMiddleware</span></tt> as described above)</div>
<div class="section" id="s-ajax">
<span id="ajax"></span><h3>AJAX<a class="headerlink" href="#ajax" title="Permalink to this headline">¶</a></h3>
<p>While the above method can be used with AJAX POST requests, it has some
inconveniences: you have to remember to get the CSRF token from the HTML
document and pass it in as POST data with every POST request. For this reason,
there is an alternative method: on each XMLHttpRequest, set a custom
<cite>X-CSRFToken</cite> 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. In jQuery, you can use the <tt class="docutils literal"><span class="pre">beforeSend</span></tt> hook as follows:</p>
<div class="highlight-javascript"><div class="highlight"><pre><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="p">(</span><span class="sr">/^http:.*/</span><span class="p">.</span><span class="nx">test</span><span class="p">(</span><span class="nx">settings</span><span class="p">.</span><span class="nx">url</span><span class="p">)</span> <span class="o">||</span> <span class="sr">/^https:.*/</span><span class="p">.</span><span class="nx">test</span><span class="p">(</span><span class="nx">settings</span><span class="p">.</span><span class="nx">url</span><span class="p">)))</span> <span class="p">{</span>
            <span class="c1">// Only send the token to relative URLs i.e. locally.</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">$</span><span class="p">(</span><span class="s2">&quot;#csrfmiddlewaretoken&quot;</span><span class="p">).</span><span class="nx">val</span><span class="p">());</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">});</span>
</pre></div>
</div>
<p>Adding this to a javascript file that is included on your site will ensure that
AJAX POST requests that are made via jQuery will not be caught by the CSRF
protection. This will only work if you remember to include a form on the page,
so that the input with id 'csrfmiddlewaretoken' will be found.</p>
</div>
<div class="section" id="s-exceptions">
<span id="exceptions"></span><h3>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.1:</span> <a class="reference external" href="../../releases/1.1.html#releases-1-1"><em>Please, see the release notes</em></a></div>
<p>To manually exclude a view function from being handled by the
CsrfMiddleware, you can use the <tt class="docutils literal"><span class="pre">csrf_exempt</span></tt> decorator, found in
the <tt class="docutils literal"><span class="pre">django.contrib.csrf.middleware</span></tt> module. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.contrib.csrf.middleware</span> <span class="kn">import</span> <span class="n">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="s">&#39;Hello world&#39;</span><span class="p">)</span>
<span class="n">my_view</span> <span class="o">=</span> <span class="n">csrf_exempt</span><span class="p">(</span><span class="n">my_view</span><span class="p">)</span>
</pre></div>
</div>
<p>Like the middleware itself, the <tt class="docutils literal"><span class="pre">csrf_exempt</span></tt> decorator is composed
of two parts: a <tt class="docutils literal"><span class="pre">csrf_view_exempt</span></tt> decorator and a
<tt class="docutils literal"><span class="pre">csrf_response_exempt</span></tt> decorator, found in the same module.  These
disable the view protection mechanism (<tt class="docutils literal"><span class="pre">CsrfViewMiddleware</span></tt>) and the
response post-processing (<tt class="docutils literal"><span class="pre">CsrfResponseMiddleware</span></tt>) respectively.
They can be used individually if required.</p>
</div>
</div>
<div class="section" id="s-how-it-works">
<span id="how-it-works"></span><h2>How it works<a class="headerlink" href="#how-it-works" title="Permalink to this headline">¶</a></h2>
<p>CsrfMiddleware does two things:</p>
<ol class="arabic simple">
<li>It modifies outgoing requests by adding a hidden form field to all
'POST' forms, with the name 'csrfmiddlewaretoken' and a value which is
a hash of the session ID plus a secret. If there is no session ID set,
this modification of the response isn't done, so there is very little
performance penalty for those requests that don't have a session.
(This is done by <tt class="docutils literal"><span class="pre">CsrfResponseMiddleware</span></tt>).</li>
<li>On all incoming POST requests that have the session cookie set, it
checks that the 'csrfmiddlewaretoken' is present and correct. If it
isn't, the user will get a 403 error. (This is done by
<tt class="docutils literal"><span class="pre">CsrfViewMiddleware</span></tt>)</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 only targets HTTP POST requests (and the corresponding POST
forms). GET requests ought never to have any potentially dangerous side
effects (see <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">9.1.1 Safe Methods, HTTP 1.1, RFC 2616</a>), and so a
CSRF attack with a GET request ought to be harmless.</p>
<p>POST requests that are not accompanied by a session cookie are not protected,
but since these requests are not authenticated, they will usually be of limited
risk.</p>
<p>The Content-Type is checked before modifying the response, and only
pages that are served as 'text/html' or 'application/xml+xhtml'
are modified.</p>
</div>
<div class="section" id="s-limitations">
<span id="limitations"></span><h2>Limitations<a class="headerlink" href="#limitations" title="Permalink to this headline">¶</a></h2>
<p>CsrfMiddleware requires Django's session framework to work. If you have
a custom authentication system that manually sets cookies and the like,
it won't help you.</p>
<p>The middleware only partially protects against 'Login CSRF'.  If you have used
standard Django views for logging in, then you will be protected, due to the way
they work (the session must be established in the step before actually logging
in, so the login step itself is protected).  If you have used a different way to
log in, you may be vulnerable to Login CSRF.</p>
<p>If your app creates HTML pages and forms in some unusual way, (e.g.
it sends fragments of HTML in JavaScript document.write statements)
you might bypass the filter that adds the hidden field to the form,
in which case form submission will always fail.  It may still be possible
to use the middleware, provided you can find some way to get the
CSRF token and ensure that is included when your form is submitted.</p>
</div>
</div>


          </div>         
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">Cross Site Request Forgery protection</a><ul>
<li><a class="reference external" href="#how-to-use-it">How to use it</a><ul>
<li><a class="reference external" href="#ajax">AJAX</a></li>
<li><a class="reference external" href="#exceptions">Exceptions</a></li>
</ul>
</li>
<li><a class="reference external" href="#how-it-works">How it works</a></li>
<li><a class="reference external" href="#limitations">Limitations</a></li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="contenttypes.html">The contenttypes framework</a></li>
    
    
      <li>Next: <a href="databrowse.html">Databrowse</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django v1.1 documentation</a>
        
          <ul><li><a href="../index.html">API Reference</a>
        
          <ul><li><a href="index.html"><tt class="docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal docutils literal"><span class="pre">contrib</span></tt> packages</a>
        
        <ul><li>Cross Site Request Forgery protection</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>  

            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../../_sources/ref/contrib/csrf.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Feb 18, 2011</p>
          </div> 
        
      
    </div>
    
    <div id="ft">
      <div class="nav">
    &laquo; <a href="contenttypes.html" title="The contenttypes framework">previous</a> 
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="databrowse.html" title="Databrowse">next</a> &raquo;</div>
    </div>
  </div>

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