<!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>Password management in Django — 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="Customizing authentication in Django" href="customizing.html" /> <link rel="prev" title="Using the Django authentication system" href="default.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 = "../../ref/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="default.html" title="Using the Django authentication system">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="customizing.html" title="Customizing authentication in Django">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-auth-passwords"> <div class="section" id="s-password-management-in-django"> <span id="password-management-in-django"></span><h1>Password management in Django<a class="headerlink" href="#password-management-in-django" title="Permalink to this headline">¶</a></h1> <p>Password management is something that should generally not be reinvented unnecessarily, and Django endeavors to provide a secure and flexible set of tools for managing user passwords. This document describes how Django stores passwords, how the storage hashing can be configured, and some utilities to work with hashed passwords.</p> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">Even though users may use strong passwords, attackers might be able to eavesdrop on their connections. Use <a class="reference internal" href="../security.html#security-recommendation-ssl"><span class="std std-ref">HTTPS</span></a> to avoid sending passwords (or any other sensitive data) over plain HTTP connections because they will be vulnerable to password sniffing.</p> </div> <div class="section" id="s-how-django-stores-passwords"> <span id="s-auth-password-storage"></span><span id="how-django-stores-passwords"></span><span id="auth-password-storage"></span><h2>How Django stores passwords<a class="headerlink" href="#how-django-stores-passwords" title="Permalink to this headline">¶</a></h2> <p>Django provides a flexible password storage system and uses PBKDF2 by default.</p> <p>The <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.password" title="django.contrib.auth.models.User.password"><code class="xref py py-attr docutils literal notranslate"><span class="pre">password</span></code></a> attribute of a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> object is a string in this format:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><algorithm>$<iterations>$<salt>$<hash> </pre></div> </div> <p>Those are the components used for storing a User’s password, separated by the dollar-sign character and consist of: the hashing algorithm, the number of algorithm iterations (work factor), the random salt, and the resulting password hash. The algorithm is one of a number of one-way hashing or password storage algorithms Django can use; see below. Iterations describe the number of times the algorithm is run over the hash. Salt is the random seed used and the hash is the result of the one-way function.</p> <p>By default, Django uses the <a class="reference external" href="https://en.wikipedia.org/wiki/PBKDF2">PBKDF2</a> algorithm with a SHA256 hash, a password stretching mechanism recommended by <a class="reference external" href="https://dx.doi.org/10.6028/NIST.SP.800-132">NIST</a>. This should be sufficient for most users: it’s quite secure, requiring massive amounts of computing time to break.</p> <p>However, depending on your requirements, you may choose a different algorithm, or even use a custom algorithm to match your specific security situation. Again, most users shouldn’t need to do this – if you’re not sure, you probably don’t. If you do, please read on:</p> <p>Django chooses the algorithm to use by consulting the <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a> setting. This is a list of hashing algorithm classes that this Django installation supports. The first entry in this list (that is, <code class="docutils literal notranslate"><span class="pre">settings.PASSWORD_HASHERS[0]</span></code>) will be used to store passwords, and all the other entries are valid hashers that can be used to check existing passwords. This means that if you want to use a different algorithm, you’ll need to modify <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a> to list your preferred algorithm first in the list.</p> <p>The default for <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a> is:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">PASSWORD_HASHERS</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.Argon2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptSHA256PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptPasswordHasher'</span><span class="p">,</span> <span class="p">]</span> </pre></div> </div> <p>This means that Django will use <a class="reference external" href="https://en.wikipedia.org/wiki/PBKDF2">PBKDF2</a> to store all passwords but will support checking passwords stored with PBKDF2SHA1, <a class="reference external" href="https://en.wikipedia.org/wiki/Argon2">argon2</a>, and <a class="reference external" href="https://en.wikipedia.org/wiki/Bcrypt">bcrypt</a>.</p> <p>The next few sections describe a couple of common ways advanced users may want to modify this setting.</p> <div class="section" id="s-using-argon2-with-django"> <span id="s-argon2-usage"></span><span id="using-argon2-with-django"></span><span id="argon2-usage"></span><h3>Using Argon2 with Django<a class="headerlink" href="#using-argon2-with-django" title="Permalink to this headline">¶</a></h3> <div class="versionadded"> <span class="title">New in Django 1.10.</span> </div> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Argon2">Argon2</a> is the winner of the 2015 <a class="reference external" href="https://password-hashing.net">Password Hashing Competition</a>, a community organized open competition to select a next generation hashing algorithm. It’s designed not to be easier to compute on custom hardware than it is to compute on an ordinary CPU.</p> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Argon2">Argon2</a> is not the default for Django because it requires a third-party library. The Password Hashing Competition panel, however, recommends immediate use of Argon2 rather than the other algorithms supported by Django.</p> <p>To use Argon2 as your default storage algorithm, do the following:</p> <ol class="arabic"> <li><p class="first">Install the <a class="reference external" href="https://pypi.python.org/pypi/argon2_cffi/">argon2-cffi library</a>. This can be done by running <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">django[argon2]</span></code>, which is equivalent to <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">argon2-cffi</span></code> (along with any version requirement from Django’s <code class="docutils literal notranslate"><span class="pre">setup.py</span></code>).</p> </li> <li><p class="first">Modify <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a> to list <code class="docutils literal notranslate"><span class="pre">Argon2PasswordHasher</span></code> first. That is, in your settings file, you’d put:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">PASSWORD_HASHERS</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'django.contrib.auth.hashers.Argon2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptSHA256PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptPasswordHasher'</span><span class="p">,</span> <span class="p">]</span> </pre></div> </div> <p>Keep and/or add any entries in this list if you need Django to <a class="reference internal" href="#password-upgrades"><span class="std std-ref">upgrade passwords</span></a>.</p> </li> </ol> </div> <div class="section" id="s-using-bcrypt-with-django"> <span id="s-bcrypt-usage"></span><span id="using-bcrypt-with-django"></span><span id="bcrypt-usage"></span><h3>Using <code class="docutils literal notranslate"><span class="pre">bcrypt</span></code> with Django<a class="headerlink" href="#using-bcrypt-with-django" title="Permalink to this headline">¶</a></h3> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Bcrypt">Bcrypt</a> is a popular password storage algorithm that’s specifically designed for long-term password storage. It’s not the default used by Django since it requires the use of third-party libraries, but since many people may want to use it Django supports bcrypt with minimal effort.</p> <p>To use Bcrypt as your default storage algorithm, do the following:</p> <ol class="arabic"> <li><p class="first">Install the <a class="reference external" href="https://pypi.python.org/pypi/bcrypt/">bcrypt library</a>. This can be done by running <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">django[bcrypt]</span></code>, which is equivalent to <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">bcrypt</span></code> (along with any version requirement from Django’s <code class="docutils literal notranslate"><span class="pre">setup.py</span></code>).</p> </li> <li><p class="first">Modify <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a> to list <code class="docutils literal notranslate"><span class="pre">BCryptSHA256PasswordHasher</span></code> first. That is, in your settings file, you’d put:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">PASSWORD_HASHERS</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'django.contrib.auth.hashers.BCryptSHA256PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptPasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.Argon2PasswordHasher'</span><span class="p">,</span> <span class="p">]</span> </pre></div> </div> <p>Keep and/or add any entries in this list if you need Django to <a class="reference internal" href="#password-upgrades"><span class="std std-ref">upgrade passwords</span></a>.</p> </li> </ol> <p>That’s it – now your Django install will use Bcrypt as the default storage algorithm.</p> <div class="admonition-password-truncation-with-bcryptpasswordhasher admonition"> <p class="first admonition-title">Password truncation with BCryptPasswordHasher</p> <p class="last">The designers of bcrypt truncate all passwords at 72 characters which means that <code class="docutils literal notranslate"><span class="pre">bcrypt(password_with_100_chars)</span> <span class="pre">==</span> <span class="pre">bcrypt(password_with_100_chars[:72])</span></code>. The original <code class="docutils literal notranslate"><span class="pre">BCryptPasswordHasher</span></code> does not have any special handling and thus is also subject to this hidden password length limit. <code class="docutils literal notranslate"><span class="pre">BCryptSHA256PasswordHasher</span></code> fixes this by first hashing the password using sha256. This prevents the password truncation and so should be preferred over the <code class="docutils literal notranslate"><span class="pre">BCryptPasswordHasher</span></code>. The practical ramification of this truncation is pretty marginal as the average user does not have a password greater than 72 characters in length and even being truncated at 72 the compute powered required to brute force bcrypt in any useful amount of time is still astronomical. Nonetheless, we recommend you use <code class="docutils literal notranslate"><span class="pre">BCryptSHA256PasswordHasher</span></code> anyway on the principle of “better safe than sorry”.</p> </div> <div class="admonition-other-bcrypt-implementations admonition"> <p class="first admonition-title">Other bcrypt implementations</p> <p class="last">There are several other implementations that allow bcrypt to be used with Django. Django’s bcrypt support is NOT directly compatible with these. To upgrade, you will need to modify the hashes in your database to be in the form <code class="docutils literal notranslate"><span class="pre">bcrypt$(raw</span> <span class="pre">bcrypt</span> <span class="pre">output)</span></code>. For example: <code class="docutils literal notranslate"><span class="pre">bcrypt$$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy</span></code>.</p> </div> </div> <div class="section" id="s-increasing-the-work-factor"> <span id="s-increasing-password-algorithm-work-factor"></span><span id="increasing-the-work-factor"></span><span id="increasing-password-algorithm-work-factor"></span><h3>Increasing the work factor<a class="headerlink" href="#increasing-the-work-factor" title="Permalink to this headline">¶</a></h3> <div class="section" id="s-pbkdf2-and-bcrypt"> <span id="pbkdf2-and-bcrypt"></span><h4>PBKDF2 and bcrypt<a class="headerlink" href="#pbkdf2-and-bcrypt" title="Permalink to this headline">¶</a></h4> <p>The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of hashing. This deliberately slows down attackers, making attacks against hashed passwords harder. However, as computing power increases, the number of iterations needs to be increased. We’ve chosen a reasonable default (and will increase it with each release of Django), but you may wish to tune it up or down, depending on your security needs and available processing power. To do so, you’ll subclass the appropriate algorithm and override the <code class="docutils literal notranslate"><span class="pre">iterations</span></code> parameters. For example, to increase the number of iterations used by the default PBKDF2 algorithm:</p> <ol class="arabic"> <li><p class="first">Create a subclass of <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.hashers.PBKDF2PasswordHasher</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.hashers</span> <span class="k">import</span> <span class="n">PBKDF2PasswordHasher</span> <span class="k">class</span> <span class="nc">MyPBKDF2PasswordHasher</span><span class="p">(</span><span class="n">PBKDF2PasswordHasher</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.</span> <span class="sd"> """</span> <span class="n">iterations</span> <span class="o">=</span> <span class="n">PBKDF2PasswordHasher</span><span class="o">.</span><span class="n">iterations</span> <span class="o">*</span> <span class="mi">100</span> </pre></div> </div> <p>Save this somewhere in your project. For example, you might put this in a file like <code class="docutils literal notranslate"><span class="pre">myproject/hashers.py</span></code>.</p> </li> <li><p class="first">Add your new hasher as the first entry in <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">PASSWORD_HASHERS</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'myproject.hashers.MyPBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.Argon2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptSHA256PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptPasswordHasher'</span><span class="p">,</span> <span class="p">]</span> </pre></div> </div> </li> </ol> <p>That’s it – now your Django install will use more iterations when it stores passwords using PBKDF2.</p> </div> <div class="section" id="s-argon2"> <span id="argon2"></span><h4>Argon2<a class="headerlink" href="#argon2" title="Permalink to this headline">¶</a></h4> <p>Argon2 has three attributes that can be customized:</p> <ol class="arabic simple"> <li><code class="docutils literal notranslate"><span class="pre">time_cost</span></code> controls the number of iterations within the hash.</li> <li><code class="docutils literal notranslate"><span class="pre">memory_cost</span></code> controls the size of memory that must be used during the computation of the hash.</li> <li><code class="docutils literal notranslate"><span class="pre">parallelism</span></code> controls how many CPUs the computation of the hash can be parallelized on.</li> </ol> <p>The default values of these attributes are probably fine for you. If you determine that the password hash is too fast or too slow, you can tweak it as follows:</p> <ol class="arabic simple"> <li>Choose <code class="docutils literal notranslate"><span class="pre">parallelism</span></code> to be the number of threads you can spare computing the hash.</li> <li>Choose <code class="docutils literal notranslate"><span class="pre">memory_cost</span></code> to be the KiB of memory you can spare.</li> <li>Adjust <code class="docutils literal notranslate"><span class="pre">time_cost</span></code> and measure the time hashing a password takes. Pick a <code class="docutils literal notranslate"><span class="pre">time_cost</span></code> that takes an acceptable time for you. If <code class="docutils literal notranslate"><span class="pre">time_cost</span></code> set to 1 is unacceptably slow, lower <code class="docutils literal notranslate"><span class="pre">memory_cost</span></code>.</li> </ol> <div class="admonition-memory-cost-interpretation admonition"> <p class="first admonition-title"><code class="docutils literal notranslate"><span class="pre">memory_cost</span></code> interpretation</p> <p class="last">The argon2 command-line utility and some other libraries interpret the <code class="docutils literal notranslate"><span class="pre">memory_cost</span></code> parameter differently from the value that Django uses. The conversion is given by <code class="docutils literal notranslate"><span class="pre">memory_cost</span> <span class="pre">==</span> <span class="pre">2</span> <span class="pre">**</span> <span class="pre">memory_cost_commandline</span></code>.</p> </div> </div> </div> <div class="section" id="s-password-upgrading"> <span id="s-password-upgrades"></span><span id="password-upgrading"></span><span id="password-upgrades"></span><h3>Password upgrading<a class="headerlink" href="#password-upgrading" title="Permalink to this headline">¶</a></h3> <p>When users log in, if their passwords are stored with anything other than the preferred algorithm, Django will automatically upgrade the algorithm to the preferred one. This means that old installs of Django will get automatically more secure as users log in, and it also means that you can switch to new (and better) storage algorithms as they get invented.</p> <p>However, Django can only upgrade passwords that use algorithms mentioned in <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a>, so as you upgrade to new systems you should make sure never to <em>remove</em> entries from this list. If you do, users using unmentioned algorithms won’t be able to upgrade. Hashed passwords will be updated when increasing (or decreasing) the number of PBKDF2 iterations or bcrypt rounds.</p> <p>Be aware that if all the passwords in your database aren’t encoded in the default hasher’s algorithm, you may be vulnerable to a user enumeration timing attack due to a difference between the duration of a login request for a user with a password encoded in a non-default algorithm and the duration of a login request for a nonexistent user (which runs the default hasher). You may be able to mitigate this by <a class="reference internal" href="#wrapping-password-hashers"><span class="std std-ref">upgrading older password hashes</span></a>.</p> </div> <div class="section" id="s-password-upgrading-without-requiring-a-login"> <span id="s-wrapping-password-hashers"></span><span id="password-upgrading-without-requiring-a-login"></span><span id="wrapping-password-hashers"></span><h3>Password upgrading without requiring a login<a class="headerlink" href="#password-upgrading-without-requiring-a-login" title="Permalink to this headline">¶</a></h3> <p>If you have an existing database with an older, weak hash such as MD5 or SHA1, you might want to upgrade those hashes yourself instead of waiting for the upgrade to happen when a user logs in (which may never happen if a user doesn’t return to your site). In this case, you can use a “wrapped” password hasher.</p> <p>For this example, we’ll migrate a collection of SHA1 hashes to use PBKDF2(SHA1(password)) and add the corresponding password hasher for checking if a user entered the correct password on login. We assume we’re using the built-in <code class="docutils literal notranslate"><span class="pre">User</span></code> model and that our project has an <code class="docutils literal notranslate"><span class="pre">accounts</span></code> app. You can modify the pattern to work with any algorithm or with a custom user model.</p> <p>First, we’ll add the custom hasher:</p> <div class="highlight-default snippet"><div class="snippet-filename">accounts/hashers.py</div> <div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.hashers</span> <span class="k">import</span> <span class="p">(</span> <span class="n">PBKDF2PasswordHasher</span><span class="p">,</span> <span class="n">SHA1PasswordHasher</span><span class="p">,</span> <span class="p">)</span> <span class="k">class</span> <span class="nc">PBKDF2WrappedSHA1PasswordHasher</span><span class="p">(</span><span class="n">PBKDF2PasswordHasher</span><span class="p">):</span> <span class="n">algorithm</span> <span class="o">=</span> <span class="s1">'pbkdf2_wrapped_sha1'</span> <span class="k">def</span> <span class="nf">encode_sha1_hash</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sha1_hash</span><span class="p">,</span> <span class="n">salt</span><span class="p">,</span> <span class="n">iterations</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">PBKDF2WrappedSHA1PasswordHasher</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">sha1_hash</span><span class="p">,</span> <span class="n">salt</span><span class="p">,</span> <span class="n">iterations</span><span class="p">)</span> <span class="k">def</span> <span class="nf">encode</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">password</span><span class="p">,</span> <span class="n">salt</span><span class="p">,</span> <span class="n">iterations</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">sha1_hash</span> <span class="o">=</span> <span class="n">SHA1PasswordHasher</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">password</span><span class="p">,</span> <span class="n">salt</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">'$'</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">encode_sha1_hash</span><span class="p">(</span><span class="n">sha1_hash</span><span class="p">,</span> <span class="n">salt</span><span class="p">,</span> <span class="n">iterations</span><span class="p">)</span> </pre></div> </div> <p>The data migration might look something like:</p> <div class="highlight-default snippet"><div class="snippet-filename">accounts/migrations/0002_migrate_sha1_passwords.py</div> <div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">migrations</span> <span class="kn">from</span> <span class="nn">..hashers</span> <span class="k">import</span> <span class="n">PBKDF2WrappedSHA1PasswordHasher</span> <span class="k">def</span> <span class="nf">forwards_func</span><span class="p">(</span><span class="n">apps</span><span class="p">,</span> <span class="n">schema_editor</span><span class="p">):</span> <span class="n">User</span> <span class="o">=</span> <span class="n">apps</span><span class="o">.</span><span class="n">get_model</span><span class="p">(</span><span class="s1">'auth'</span><span class="p">,</span> <span class="s1">'User'</span><span class="p">)</span> <span class="n">users</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">password__startswith</span><span class="o">=</span><span class="s1">'sha1$'</span><span class="p">)</span> <span class="n">hasher</span> <span class="o">=</span> <span class="n">PBKDF2WrappedSHA1PasswordHasher</span><span class="p">()</span> <span class="k">for</span> <span class="n">user</span> <span class="ow">in</span> <span class="n">users</span><span class="p">:</span> <span class="n">algorithm</span><span class="p">,</span> <span class="n">salt</span><span class="p">,</span> <span class="n">sha1_hash</span> <span class="o">=</span> <span class="n">user</span><span class="o">.</span><span class="n">password</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">'$'</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">password</span> <span class="o">=</span> <span class="n">hasher</span><span class="o">.</span><span class="n">encode_sha1_hash</span><span class="p">(</span><span class="n">sha1_hash</span><span class="p">,</span> <span class="n">salt</span><span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">update_fields</span><span class="o">=</span><span class="p">[</span><span class="s1">'password'</span><span class="p">])</span> <span class="k">class</span> <span class="nc">Migration</span><span class="p">(</span><span class="n">migrations</span><span class="o">.</span><span class="n">Migration</span><span class="p">):</span> <span class="n">dependencies</span> <span class="o">=</span> <span class="p">[</span> <span class="p">(</span><span class="s1">'accounts'</span><span class="p">,</span> <span class="s1">'0001_initial'</span><span class="p">),</span> <span class="c1"># replace this with the latest migration in contrib.auth</span> <span class="p">(</span><span class="s1">'auth'</span><span class="p">,</span> <span class="s1">'####_migration_name'</span><span class="p">),</span> <span class="p">]</span> <span class="n">operations</span> <span class="o">=</span> <span class="p">[</span> <span class="n">migrations</span><span class="o">.</span><span class="n">RunPython</span><span class="p">(</span><span class="n">forwards_func</span><span class="p">),</span> <span class="p">]</span> </pre></div> </div> <p>Be aware that this migration will take on the order of several minutes for several thousand users, depending on the speed of your hardware.</p> <p>Finally, we’ll add a <a class="reference internal" href="../../ref/settings.html#std:setting-PASSWORD_HASHERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code></a> setting:</p> <div class="highlight-default snippet"><div class="snippet-filename">mysite/settings.py</div> <div class="highlight"><pre><span></span><span class="n">PASSWORD_HASHERS</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'accounts.hashers.PBKDF2WrappedSHA1PasswordHasher'</span><span class="p">,</span> <span class="p">]</span> </pre></div> </div> <p>Include any other hashers that your site uses in this list.</p> </div> <div class="section" id="s-included-hashers"> <span id="s-auth-included-hashers"></span><span id="included-hashers"></span><span id="auth-included-hashers"></span><h3>Included hashers<a class="headerlink" href="#included-hashers" title="Permalink to this headline">¶</a></h3> <p>The full list of hashers included in Django is:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.Argon2PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptSHA256PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.BCryptPasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.SHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.MD5PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher'</span><span class="p">,</span> <span class="s1">'django.contrib.auth.hashers.CryptPasswordHasher'</span><span class="p">,</span> <span class="p">]</span> </pre></div> </div> <p>The corresponding algorithm names are:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">pbkdf2_sha256</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">pbkdf2_sha1</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">argon2</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">bcrypt_sha256</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">bcrypt</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">sha1</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">md5</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">unsalted_sha1</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">unsalted_md5</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">crypt</span></code></li> </ul> </div> <div class="section" id="s-writing-your-own-hasher"> <span id="s-write-your-own-password-hasher"></span><span id="writing-your-own-hasher"></span><span id="write-your-own-password-hasher"></span><h3>Writing your own hasher<a class="headerlink" href="#writing-your-own-hasher" title="Permalink to this headline">¶</a></h3> <p>If you write your own password hasher that contains a work factor such as a number of iterations, you should implement a <code class="docutils literal notranslate"><span class="pre">harden_runtime(self,</span> <span class="pre">password,</span> <span class="pre">encoded)</span></code> method to bridge the runtime gap between the work factor supplied in the <code class="docutils literal notranslate"><span class="pre">encoded</span></code> password and the default work factor of the hasher. This prevents a user enumeration timing attack due to difference between a login request for a user with a password encoded in an older number of iterations and a nonexistent user (which runs the default hasher’s default number of iterations).</p> <p>Taking PBKDF2 as example, if <code class="docutils literal notranslate"><span class="pre">encoded</span></code> contains 20,000 iterations and the hasher’s default <code class="docutils literal notranslate"><span class="pre">iterations</span></code> is 30,000, the method should run <code class="docutils literal notranslate"><span class="pre">password</span></code> through another 10,000 iterations of PBKDF2.</p> <p>If your hasher doesn’t have a work factor, implement the method as a no-op (<code class="docutils literal notranslate"><span class="pre">pass</span></code>).</p> </div> </div> <div class="section" id="s-module-django.contrib.auth.hashers"> <span id="s-manually-managing-a-user-s-password"></span><span id="module-django.contrib.auth.hashers"></span><span id="manually-managing-a-user-s-password"></span><h2>Manually managing a user’s password<a class="headerlink" href="#module-django.contrib.auth.hashers" title="Permalink to this headline">¶</a></h2> <p>The <a class="reference internal" href="#module-django.contrib.auth.hashers" title="django.contrib.auth.hashers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.auth.hashers</span></code></a> module provides a set of functions to create and validate hashed password. You can use them independently from the <code class="docutils literal notranslate"><span class="pre">User</span></code> model.</p> <dl class="function"> <dt id="django.contrib.auth.hashers.check_password"> <code class="descname">check_password</code>(<em>password</em>, <em>encoded</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/hashers.html#check_password"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.hashers.check_password" title="Permalink to this definition">¶</a></dt> <dd><p>If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function <a class="reference internal" href="#django.contrib.auth.hashers.check_password" title="django.contrib.auth.hashers.check_password"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_password()</span></code></a>. It takes two arguments: the plain-text password to check, and the full value of a user’s <code class="docutils literal notranslate"><span class="pre">password</span></code> field in the database to check against, and returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if they match, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.hashers.make_password"> <code class="descname">make_password</code>(<em>password</em>, <em>salt=None</em>, <em>hasher='default'</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/hashers.html#make_password"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.hashers.make_password" title="Permalink to this definition">¶</a></dt> <dd><p>Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text. Optionally, you can provide a salt and a hashing algorithm to use, if you don’t want to use the defaults (first entry of <code class="docutils literal notranslate"><span class="pre">PASSWORD_HASHERS</span></code> setting). See <a class="reference internal" href="#auth-included-hashers"><span class="std std-ref">Included hashers</span></a> for the algorithm name of each hasher. If the password argument is <code class="docutils literal notranslate"><span class="pre">None</span></code>, an unusable password is returned (a one that will be never accepted by <a class="reference internal" href="#django.contrib.auth.hashers.check_password" title="django.contrib.auth.hashers.check_password"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_password()</span></code></a>).</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.hashers.is_password_usable"> <code class="descname">is_password_usable</code>(<em>encoded_password</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/hashers.html#is_password_usable"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.hashers.is_password_usable" title="Permalink to this definition">¶</a></dt> <dd><p>Checks if the given string is a hashed password that has a chance of being verified against <a class="reference internal" href="#django.contrib.auth.hashers.check_password" title="django.contrib.auth.hashers.check_password"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_password()</span></code></a>.</p> </dd></dl> </div> <div class="section" id="s-module-django.contrib.auth.password_validation"> <span id="s-id2"></span><span id="s-password-validation"></span><span id="module-django.contrib.auth.password_validation"></span><span id="id2"></span><span id="password-validation"></span><h2>Password validation<a class="headerlink" href="#module-django.contrib.auth.password_validation" title="Permalink to this headline">¶</a></h2> <p>Users often choose poor passwords. To help mitigate this problem, Django offers pluggable password validation. You can configure multiple password validators at the same time. A few validators are included in Django, but it’s simple to write your own as well.</p> <p>Each password validator must provide a help text to explain the requirements to the user, validate a given password and return an error message if it does not meet the requirements, and optionally receive passwords that have been set. Validators can also have optional settings to fine tune their behavior.</p> <p>Validation is controlled by the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a> setting. The default for the setting is an empty list, which means no validators are applied. In new projects created with the default <a class="reference internal" href="../../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">startproject</span></code></a> template, a simple set of validators is enabled.</p> <p>By default, validators are used in the forms to reset or change passwords and in the <a class="reference internal" href="../../ref/django-admin.html#django-admin-createsuperuser"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createsuperuser</span></code></a> and <a class="reference internal" href="../../ref/django-admin.html#django-admin-changepassword"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">changepassword</span></code></a> management commands. Validators aren’t applied at the model level, for example in <code class="docutils literal notranslate"><span class="pre">User.objects.create_user()</span></code> and <code class="docutils literal notranslate"><span class="pre">create_superuser()</span></code>, because we assume that developers, not users, interact with Django at that level and also because model validation doesn’t automatically run as part of creating models.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Password validation can prevent the use of many types of weak passwords. However, the fact that a password passes all the validators doesn’t guarantee that it is a strong password. There are many factors that can weaken a password that are not detectable by even the most advanced password validators.</p> </div> <div class="section" id="s-enabling-password-validation"> <span id="enabling-password-validation"></span><h3>Enabling password validation<a class="headerlink" href="#enabling-password-validation" title="Permalink to this headline">¶</a></h3> <p>Password validation is configured in the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a> setting:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">AUTH_PASSWORD_VALIDATORS</span> <span class="o">=</span> <span class="p">[</span> <span class="p">{</span> <span class="s1">'NAME'</span><span class="p">:</span> <span class="s1">'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'</span><span class="p">,</span> <span class="p">},</span> <span class="p">{</span> <span class="s1">'NAME'</span><span class="p">:</span> <span class="s1">'django.contrib.auth.password_validation.MinimumLengthValidator'</span><span class="p">,</span> <span class="s1">'OPTIONS'</span><span class="p">:</span> <span class="p">{</span> <span class="s1">'min_length'</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span> <span class="p">}</span> <span class="p">},</span> <span class="p">{</span> <span class="s1">'NAME'</span><span class="p">:</span> <span class="s1">'django.contrib.auth.password_validation.CommonPasswordValidator'</span><span class="p">,</span> <span class="p">},</span> <span class="p">{</span> <span class="s1">'NAME'</span><span class="p">:</span> <span class="s1">'django.contrib.auth.password_validation.NumericPasswordValidator'</span><span class="p">,</span> <span class="p">},</span> <span class="p">]</span> </pre></div> </div> <p>This example enables all four included validators:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">UserAttributeSimilarityValidator</span></code>, which checks the similarity between the password and a set of attributes of the user.</li> <li><code class="docutils literal notranslate"><span class="pre">MinimumLengthValidator</span></code>, which simply checks whether the password meets a minimum length. This validator is configured with a custom option: it now requires the minimum length to be nine characters, instead of the default eight.</li> <li><code class="docutils literal notranslate"><span class="pre">CommonPasswordValidator</span></code>, which checks whether the password occurs in a list of common passwords. By default, it compares to an included list of 1000 common passwords.</li> <li><code class="docutils literal notranslate"><span class="pre">NumericPasswordValidator</span></code>, which checks whether the password isn’t entirely numeric.</li> </ul> <p>For <code class="docutils literal notranslate"><span class="pre">UserAttributeSimilarityValidator</span></code> and <code class="docutils literal notranslate"><span class="pre">CommonPasswordValidator</span></code>, we’re simply using the default settings in this example. <code class="docutils literal notranslate"><span class="pre">NumericPasswordValidator</span></code> has no settings.</p> <p>The help texts and any errors from password validators are always returned in the order they are listed in <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a>.</p> </div> <div class="section" id="s-included-validators"> <span id="included-validators"></span><h3>Included validators<a class="headerlink" href="#included-validators" title="Permalink to this headline">¶</a></h3> <p>Django includes four validators:</p> <dl class="class"> <dt id="django.contrib.auth.password_validation.MinimumLengthValidator"> <em class="property">class </em><code class="descname">MinimumLengthValidator</code>(<em>min_length=8</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#MinimumLengthValidator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.MinimumLengthValidator" title="Permalink to this definition">¶</a></dt> <dd><p>Validates whether the password meets a minimum length. The minimum length can be customized with the <code class="docutils literal notranslate"><span class="pre">min_length</span></code> parameter.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.password_validation.UserAttributeSimilarityValidator"> <em class="property">class </em><code class="descname">UserAttributeSimilarityValidator</code>(<em>user_attributes=DEFAULT_USER_ATTRIBUTES</em>, <em>max_similarity=0.7</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#UserAttributeSimilarityValidator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.UserAttributeSimilarityValidator" title="Permalink to this definition">¶</a></dt> <dd><p>Validates whether the password is sufficiently different from certain attributes of the user.</p> <p>The <code class="docutils literal notranslate"><span class="pre">user_attributes</span></code> parameter should be an iterable of names of user attributes to compare to. If this argument is not provided, the default is used: <code class="docutils literal notranslate"><span class="pre">'username',</span> <span class="pre">'first_name',</span> <span class="pre">'last_name',</span> <span class="pre">'email'</span></code>. Attributes that don’t exist are ignored.</p> <p>The minimum similarity of a rejected password can be set on a scale of 0 to 1 with the <code class="docutils literal notranslate"><span class="pre">max_similarity</span></code> parameter. A setting of 0 rejects all passwords, whereas a setting of 1 rejects only passwords that are identical to an attribute’s value.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.password_validation.CommonPasswordValidator"> <em class="property">class </em><code class="descname">CommonPasswordValidator</code>(<em>password_list_path=DEFAULT_PASSWORD_LIST_PATH</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#CommonPasswordValidator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.CommonPasswordValidator" title="Permalink to this definition">¶</a></dt> <dd><p>Validates whether the password is not a common password. By default, this checks against a list of 1000 common password created by <a class="reference external" href="https://web.archive.org/web/20150315154609/https://xato.net/passwords/more-top-worst-passwords/">Mark Burnett</a>.</p> <p>The <code class="docutils literal notranslate"><span class="pre">password_list_path</span></code> can be set to the path of a custom file of common passwords. This file should contain one password per line and may be plain text or gzipped.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.password_validation.NumericPasswordValidator"> <em class="property">class </em><code class="descname">NumericPasswordValidator</code><a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#NumericPasswordValidator"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.NumericPasswordValidator" title="Permalink to this definition">¶</a></dt> <dd><p>Validates whether the password is not entirely numeric.</p> </dd></dl> </div> <div class="section" id="s-integrating-validation"> <span id="integrating-validation"></span><h3>Integrating validation<a class="headerlink" href="#integrating-validation" title="Permalink to this headline">¶</a></h3> <p>There are a few functions in <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.password_validation</span></code> that you can call from your own forms or other code to integrate password validation. This can be useful if you use custom forms for password setting, or if you have API calls that allow passwords to be set, for example.</p> <dl class="function"> <dt id="django.contrib.auth.password_validation.validate_password"> <code class="descname">validate_password</code>(<em>password</em>, <em>user=None</em>, <em>password_validators=None</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#validate_password"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.validate_password" title="Permalink to this definition">¶</a></dt> <dd><p>Validates a password. If all validators find the password valid, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. If one or more validators reject the password, raises a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValidationError</span></code></a> with all the error messages from the validators.</p> <p>The <code class="docutils literal notranslate"><span class="pre">user</span></code> object is optional: if it’s not provided, some validators may not be able to perform any validation and will accept any password.</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.password_validation.password_changed"> <code class="descname">password_changed</code>(<em>password</em>, <em>user=None</em>, <em>password_validators=None</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#password_changed"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.password_changed" title="Permalink to this definition">¶</a></dt> <dd><p>Informs all validators that the password has been changed. This can be used by validators such as one that prevents password reuse. This should be called once the password has been successfully changed.</p> <p>For subclasses of <a class="reference internal" href="customizing.html#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a>, the password field will be marked as “dirty” when calling <a class="reference internal" href="customizing.html#django.contrib.auth.models.AbstractBaseUser.set_password" title="django.contrib.auth.models.AbstractBaseUser.set_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_password()</span></code></a> which triggers a call to <code class="docutils literal notranslate"><span class="pre">password_changed()</span></code> after the user is saved.</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.password_validation.password_validators_help_texts"> <code class="descname">password_validators_help_texts</code>(<em>password_validators=None</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#password_validators_help_texts"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.password_validators_help_texts" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a list of the help texts of all validators. These explain the password requirements to the user.</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.password_validation.password_validators_help_text_html"> <code class="descname">password_validators_help_text_html</code>(<em>password_validators=None</em>)<a class="headerlink" href="#django.contrib.auth.password_validation.password_validators_help_text_html" title="Permalink to this definition">¶</a></dt> <dd><p>Returns an HTML string with all help texts in an <code class="docutils literal notranslate"><span class="pre"><ul></span></code>. This is helpful when adding password validation to forms, as you can pass the output directly to the <code class="docutils literal notranslate"><span class="pre">help_text</span></code> parameter of a form field.</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.password_validation.get_password_validators"> <code class="descname">get_password_validators</code>(<em>validator_config</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/password_validation.html#get_password_validators"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.password_validation.get_password_validators" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a set of validator objects based on the <code class="docutils literal notranslate"><span class="pre">validator_config</span></code> parameter. By default, all functions use the validators defined in <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a>, but by calling this function with an alternate set of validators and then passing the result into the <code class="docutils literal notranslate"><span class="pre">password_validators</span></code> parameter of the other functions, your custom set of validators will be used instead. This is useful when you have a typical set of validators to use for most scenarios, but also have a special situation that requires a custom set. If you always use the same set of validators, there is no need to use this function, as the configuration from <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a> is used by default.</p> <p>The structure of <code class="docutils literal notranslate"><span class="pre">validator_config</span></code> is identical to the structure of <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a>. The return value of this function can be passed into the <code class="docutils literal notranslate"><span class="pre">password_validators</span></code> parameter of the functions listed above.</p> </dd></dl> <p>Note that where the password is passed to one of these functions, this should always be the clear text password - not a hashed password.</p> </div> <div class="section" id="s-writing-your-own-validator"> <span id="writing-your-own-validator"></span><h3>Writing your own validator<a class="headerlink" href="#writing-your-own-validator" title="Permalink to this headline">¶</a></h3> <p>If Django’s built-in validators are not sufficient, you can write your own password validators. Validators are fairly simple classes. They must implement two methods:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">validate(self,</span> <span class="pre">password,</span> <span class="pre">user=None)</span></code>: validate a password. Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if the password is valid, or raise a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValidationError</span></code></a> with an error message if the password is not valid. You must be able to deal with <code class="docutils literal notranslate"><span class="pre">user</span></code> being <code class="docutils literal notranslate"><span class="pre">None</span></code> - if that means your validator can’t run, simply return <code class="docutils literal notranslate"><span class="pre">None</span></code> for no error.</li> <li><code class="docutils literal notranslate"><span class="pre">get_help_text()</span></code>: provide a help text to explain the requirements to the user.</li> </ul> <p>Any items in the <code class="docutils literal notranslate"><span class="pre">OPTIONS</span></code> in <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_PASSWORD_VALIDATORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_PASSWORD_VALIDATORS</span></code></a> for your validator will be passed to the constructor. All constructor arguments should have a default value.</p> <p>Here’s a basic example of a validator, with one optional setting:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="k">import</span> <span class="n">ValidationError</span> <span class="kn">from</span> <span class="nn">django.utils.translation</span> <span class="k">import</span> <span class="n">ugettext</span> <span class="k">as</span> <span class="n">_</span> <span class="k">class</span> <span class="nc">MinimumLengthValidator</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">min_length</span><span class="o">=</span><span class="mi">8</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">min_length</span> <span class="o">=</span> <span class="n">min_length</span> <span class="k">def</span> <span class="nf">validate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">password</span><span class="p">,</span> <span class="n">user</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">password</span><span class="p">)</span> <span class="o"><</span> <span class="bp">self</span><span class="o">.</span><span class="n">min_length</span><span class="p">:</span> <span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span> <span class="n">_</span><span class="p">(</span><span class="s2">"This password must contain at least </span><span class="si">%(min_length)d</span><span class="s2"> characters."</span><span class="p">),</span> <span class="n">code</span><span class="o">=</span><span class="s1">'password_too_short'</span><span class="p">,</span> <span class="n">params</span><span class="o">=</span><span class="p">{</span><span class="s1">'min_length'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">min_length</span><span class="p">},</span> <span class="p">)</span> <span class="k">def</span> <span class="nf">get_help_text</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="n">_</span><span class="p">(</span> <span class="s2">"Your password must contain at least </span><span class="si">%(min_length)d</span><span class="s2"> characters."</span> <span class="o">%</span> <span class="p">{</span><span class="s1">'min_length'</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">min_length</span><span class="p">}</span> <span class="p">)</span> </pre></div> </div> <p>You can also implement <code class="docutils literal notranslate"><span class="pre">password_changed(password,</span> <span class="pre">user=None</span></code>), which will be called after a successful password change. That can be used to prevent password reuse, for example. However, if you decide to store a user’s previous passwords, you should never do so in clear text.</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="#">Password management in Django</a><ul> <li><a class="reference internal" href="#how-django-stores-passwords">How Django stores passwords</a><ul> <li><a class="reference internal" href="#using-argon2-with-django">Using Argon2 with Django</a></li> <li><a class="reference internal" href="#using-bcrypt-with-django">Using <code class="docutils literal notranslate"><span class="pre">bcrypt</span></code> with Django</a></li> <li><a class="reference internal" href="#increasing-the-work-factor">Increasing the work factor</a><ul> <li><a class="reference internal" href="#pbkdf2-and-bcrypt">PBKDF2 and bcrypt</a></li> <li><a class="reference internal" href="#argon2">Argon2</a></li> </ul> </li> <li><a class="reference internal" href="#password-upgrading">Password upgrading</a></li> <li><a class="reference internal" href="#password-upgrading-without-requiring-a-login">Password upgrading without requiring a login</a></li> <li><a class="reference internal" href="#included-hashers">Included hashers</a></li> <li><a class="reference internal" href="#writing-your-own-hasher">Writing your own hasher</a></li> </ul> </li> <li><a class="reference internal" href="#module-django.contrib.auth.hashers">Manually managing a user’s password</a></li> <li><a class="reference internal" href="#module-django.contrib.auth.password_validation">Password validation</a><ul> <li><a class="reference internal" href="#enabling-password-validation">Enabling password validation</a></li> <li><a class="reference internal" href="#included-validators">Included validators</a></li> <li><a class="reference internal" href="#integrating-validation">Integrating validation</a></li> <li><a class="reference internal" href="#writing-your-own-validator">Writing your own validator</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="default.html" title="previous chapter">Using the Django authentication system</a></p> <h4>Next topic</h4> <p class="topless"><a href="customizing.html" title="next chapter">Customizing authentication in Django</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/topics/auth/passwords.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="default.html" title="Using the Django authentication system">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="customizing.html" title="Customizing authentication in Django">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>