1. =============================
    
  2. Password management in Django
    
  3. =============================
    
  4. 
    
  5. Password management is something that should generally not be reinvented
    
  6. unnecessarily, and Django endeavors to provide a secure and flexible set of
    
  7. tools for managing user passwords. This document describes how Django stores
    
  8. passwords, how the storage hashing can be configured, and some utilities to
    
  9. work with hashed passwords.
    
  10. 
    
  11. .. seealso::
    
  12. 
    
  13.     Even though users may use strong passwords, attackers might be able to
    
  14.     eavesdrop on their connections. Use :ref:`HTTPS
    
  15.     <security-recommendation-ssl>` to avoid sending passwords (or any other
    
  16.     sensitive data) over plain HTTP connections because they will be vulnerable
    
  17.     to password sniffing.
    
  18. 
    
  19. .. _auth_password_storage:
    
  20. 
    
  21. How Django stores passwords
    
  22. ===========================
    
  23. 
    
  24. Django provides a flexible password storage system and uses PBKDF2 by default.
    
  25. 
    
  26. The :attr:`~django.contrib.auth.models.User.password` attribute of a
    
  27. :class:`~django.contrib.auth.models.User` object is a string in this format::
    
  28. 
    
  29.     <algorithm>$<iterations>$<salt>$<hash>
    
  30. 
    
  31. Those are the components used for storing a User's password, separated by the
    
  32. dollar-sign character and consist of: the hashing algorithm, the number of
    
  33. algorithm iterations (work factor), the random salt, and the resulting password
    
  34. hash.  The algorithm is one of a number of one-way hashing or password storage
    
  35. algorithms Django can use; see below. Iterations describe the number of times
    
  36. the algorithm is run over the hash. Salt is the random seed used and the hash
    
  37. is the result of the one-way function.
    
  38. 
    
  39. By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
    
  40. password stretching mechanism recommended by NIST_. This should be
    
  41. sufficient for most users: it's quite secure, requiring massive
    
  42. amounts of computing time to break.
    
  43. 
    
  44. However, depending on your requirements, you may choose a different
    
  45. algorithm, or even use a custom algorithm to match your specific
    
  46. security situation. Again, most users shouldn't need to do this -- if
    
  47. you're not sure, you probably don't.  If you do, please read on:
    
  48. 
    
  49. Django chooses the algorithm to use by consulting the
    
  50. :setting:`PASSWORD_HASHERS` setting. This is a list of hashing algorithm
    
  51. classes that this Django installation supports.
    
  52. 
    
  53. For storing passwords, Django will use the first hasher in
    
  54. :setting:`PASSWORD_HASHERS`. To store new passwords with a different algorithm,
    
  55. put your preferred algorithm first in :setting:`PASSWORD_HASHERS`.
    
  56. 
    
  57. For verifying passwords, Django will find the hasher in the list that matches
    
  58. the algorithm name in the stored password. If a stored password names an
    
  59. algorithm not found in :setting:`PASSWORD_HASHERS`, trying to verify it will
    
  60. raise ``ValueError``.
    
  61. 
    
  62. The default for :setting:`PASSWORD_HASHERS` is::
    
  63. 
    
  64.     PASSWORD_HASHERS = [
    
  65.         'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  66.         'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    
  67.         'django.contrib.auth.hashers.Argon2PasswordHasher',
    
  68.         'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    
  69.         'django.contrib.auth.hashers.ScryptPasswordHasher',
    
  70.     ]
    
  71. 
    
  72. This means that Django will use PBKDF2_ to store all passwords but will support
    
  73. checking passwords stored with PBKDF2SHA1, argon2_, and bcrypt_.
    
  74. 
    
  75. The next few sections describe a couple of common ways advanced users may want
    
  76. to modify this setting.
    
  77. 
    
  78. .. _argon2_usage:
    
  79. 
    
  80. Using Argon2 with Django
    
  81. ------------------------
    
  82. 
    
  83. Argon2_ is the winner of the 2015 `Password Hashing Competition`_, a community
    
  84. organized open competition to select a next generation hashing algorithm. It's
    
  85. designed not to be easier to compute on custom hardware than it is to compute
    
  86. on an ordinary CPU. The default variant for the Argon2 password hasher is
    
  87. Argon2id.
    
  88. 
    
  89. Argon2_ is not the default for Django because it requires a third-party
    
  90. library. The Password Hashing Competition panel, however, recommends immediate
    
  91. use of Argon2 rather than the other algorithms supported by Django.
    
  92. 
    
  93. To use Argon2id as your default storage algorithm, do the following:
    
  94. 
    
  95. #. Install the `argon2-cffi library`_.  This can be done by running
    
  96.    ``python -m pip install django[argon2]``, which is equivalent to
    
  97.    ``python -m pip install argon2-cffi`` (along with any version requirement
    
  98.    from Django's ``setup.cfg``).
    
  99. 
    
  100. #. Modify :setting:`PASSWORD_HASHERS` to list ``Argon2PasswordHasher`` first.
    
  101.    That is, in your settings file, you'd put::
    
  102. 
    
  103.         PASSWORD_HASHERS = [
    
  104.             'django.contrib.auth.hashers.Argon2PasswordHasher',
    
  105.             'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  106.             'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    
  107.             'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    
  108.             'django.contrib.auth.hashers.ScryptPasswordHasher',
    
  109.         ]
    
  110. 
    
  111.    Keep and/or add any entries in this list if you need Django to :ref:`upgrade
    
  112.    passwords <password-upgrades>`.
    
  113. 
    
  114. .. _bcrypt_usage:
    
  115. 
    
  116. Using ``bcrypt`` with Django
    
  117. ----------------------------
    
  118. 
    
  119. Bcrypt_ is a popular password storage algorithm that's specifically designed
    
  120. for long-term password storage. It's not the default used by Django since it
    
  121. requires the use of third-party libraries, but since many people may want to
    
  122. use it Django supports bcrypt with minimal effort.
    
  123. 
    
  124. To use Bcrypt as your default storage algorithm, do the following:
    
  125. 
    
  126. #. Install the `bcrypt library`_. This can be done by running
    
  127.    ``python -m pip install django[bcrypt]``, which is equivalent to
    
  128.    ``python -m pip install bcrypt`` (along with any version requirement from
    
  129.    Django's ``setup.cfg``).
    
  130. 
    
  131. #. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptSHA256PasswordHasher``
    
  132.    first. That is, in your settings file, you'd put::
    
  133. 
    
  134.         PASSWORD_HASHERS = [
    
  135.             'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    
  136.             'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  137.             'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    
  138.             'django.contrib.auth.hashers.Argon2PasswordHasher',
    
  139.             'django.contrib.auth.hashers.ScryptPasswordHasher',
    
  140.         ]
    
  141. 
    
  142.    Keep and/or add any entries in this list if you need Django to :ref:`upgrade
    
  143.    passwords <password-upgrades>`.
    
  144. 
    
  145. That's it -- now your Django install will use Bcrypt as the default storage
    
  146. algorithm.
    
  147. 
    
  148. .. _scrypt-usage:
    
  149. 
    
  150. Using ``scrypt`` with Django
    
  151. ----------------------------
    
  152. 
    
  153. .. versionadded:: 4.0
    
  154. 
    
  155. scrypt_ is similar to PBKDF2 and bcrypt in utilizing a set number of iterations
    
  156. to slow down brute-force attacks. However, because PBKDF2 and bcrypt do not
    
  157. require a lot of memory, attackers with sufficient resources can launch
    
  158. large-scale parallel attacks in order to speed up the attacking process.
    
  159. scrypt_ is specifically designed to use more memory compared to other
    
  160. password-based key derivation functions in order to limit the amount of
    
  161. parallelism an attacker can use, see :rfc:`7914` for more details.
    
  162. 
    
  163. To use scrypt_ as your default storage algorithm, do the following:
    
  164. 
    
  165. #. Modify :setting:`PASSWORD_HASHERS` to list ``ScryptPasswordHasher`` first.
    
  166.    That is, in your settings file::
    
  167. 
    
  168.         PASSWORD_HASHERS = [
    
  169.             'django.contrib.auth.hashers.ScryptPasswordHasher',
    
  170.             'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  171.             'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    
  172.             'django.contrib.auth.hashers.Argon2PasswordHasher',
    
  173.             'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    
  174.         ]
    
  175. 
    
  176.    Keep and/or add any entries in this list if you need Django to :ref:`upgrade
    
  177.    passwords <password-upgrades>`.
    
  178. 
    
  179. .. note::
    
  180. 
    
  181.     ``scrypt`` requires OpenSSL 1.1+.
    
  182. 
    
  183. Increasing the salt entropy
    
  184. ---------------------------
    
  185. 
    
  186. Most password hashes include a salt along with their password hash in order to
    
  187. protect against rainbow table attacks. The salt itself is a random value which
    
  188. increases the size and thus the cost of the rainbow table and is currently set
    
  189. at 128 bits with the ``salt_entropy`` value in the ``BasePasswordHasher``. As
    
  190. computing and storage costs decrease this value should be raised. When
    
  191. implementing your own password hasher you are free to override this value in
    
  192. order to use a desired entropy level for your password hashes. ``salt_entropy``
    
  193. is measured in bits.
    
  194. 
    
  195. .. admonition:: Implementation detail
    
  196. 
    
  197.     Due to the method in which salt values are stored the ``salt_entropy``
    
  198.     value is effectively a minimum value. For instance a value of 128 would
    
  199.     provide a salt which would actually contain 131 bits of entropy.
    
  200. 
    
  201. .. _increasing-password-algorithm-work-factor:
    
  202. 
    
  203. Increasing the work factor
    
  204. --------------------------
    
  205. 
    
  206. PBKDF2 and bcrypt
    
  207. ~~~~~~~~~~~~~~~~~
    
  208. 
    
  209. The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
    
  210. hashing. This deliberately slows down attackers, making attacks against hashed
    
  211. passwords harder. However, as computing power increases, the number of
    
  212. iterations needs to be increased. We've chosen a reasonable default (and will
    
  213. increase it with each release of Django), but you may wish to tune it up or
    
  214. down, depending on your security needs and available processing power. To do so,
    
  215. you'll subclass the appropriate algorithm and override the ``iterations``
    
  216. parameter (use the ``rounds`` parameter when subclassing a bcrypt hasher). For
    
  217. example, to increase the number of iterations used by the default PBKDF2
    
  218. algorithm:
    
  219. 
    
  220. #. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
    
  221. 
    
  222.         from django.contrib.auth.hashers import PBKDF2PasswordHasher
    
  223. 
    
  224.         class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
    
  225.             """
    
  226.             A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
    
  227.             """
    
  228.             iterations = PBKDF2PasswordHasher.iterations * 100
    
  229. 
    
  230.    Save this somewhere in your project. For example, you might put this in
    
  231.    a file like ``myproject/hashers.py``.
    
  232. 
    
  233. #. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
    
  234. 
    
  235.         PASSWORD_HASHERS = [
    
  236.             'myproject.hashers.MyPBKDF2PasswordHasher',
    
  237.             'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  238.             'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    
  239.             'django.contrib.auth.hashers.Argon2PasswordHasher',
    
  240.             'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    
  241.             'django.contrib.auth.hashers.ScryptPasswordHasher',
    
  242.         ]
    
  243. 
    
  244. That's it -- now your Django install will use more iterations when it
    
  245. stores passwords using PBKDF2.
    
  246. 
    
  247. .. note::
    
  248. 
    
  249.     bcrypt ``rounds`` is a logarithmic work factor, e.g. 12 rounds means
    
  250.     ``2 ** 12`` iterations.
    
  251. 
    
  252. Argon2
    
  253. ~~~~~~
    
  254. 
    
  255. Argon2 has the following attributes that can be customized:
    
  256. 
    
  257. #. ``time_cost`` controls the number of iterations within the hash.
    
  258. #. ``memory_cost`` controls the size of memory that must be used during the
    
  259.    computation of the hash.
    
  260. #. ``parallelism`` controls how many CPUs the computation of the hash can be
    
  261.    parallelized on.
    
  262. 
    
  263. The default values of these attributes are probably fine for you. If you
    
  264. determine that the password hash is too fast or too slow, you can tweak it as
    
  265. follows:
    
  266. 
    
  267. #. Choose ``parallelism`` to be the number of threads you can
    
  268.    spare computing the hash.
    
  269. #. Choose ``memory_cost`` to be the KiB of memory you can spare.
    
  270. #. Adjust ``time_cost`` and measure the time hashing a password takes.
    
  271.    Pick a ``time_cost`` that takes an acceptable time for you.
    
  272.    If ``time_cost`` set to 1 is unacceptably slow, lower ``memory_cost``.
    
  273. 
    
  274. .. admonition:: ``memory_cost`` interpretation
    
  275. 
    
  276.     The argon2 command-line utility and some other libraries interpret the
    
  277.     ``memory_cost`` parameter differently from the value that Django uses. The
    
  278.     conversion is given by ``memory_cost == 2 ** memory_cost_commandline``.
    
  279. 
    
  280. ``scrypt``
    
  281. ~~~~~~~~~~
    
  282. 
    
  283. .. versionadded:: 4.0
    
  284. 
    
  285. scrypt_ has the following attributes that can be customized:
    
  286. 
    
  287. #. ``work_factor`` controls the number of iterations within the hash.
    
  288. #. ``block_size``
    
  289. #. ``parallelism`` controls how many threads will run in parallel.
    
  290. #. ``maxmem`` limits the maximum size of memory that can be used during the
    
  291.    computation of the hash. Defaults to ``0``, which means the default
    
  292.    limitation from the OpenSSL library.
    
  293. 
    
  294. We've chosen reasonable defaults, but you may wish to tune it up or down,
    
  295. depending on your security needs and available processing power.
    
  296. 
    
  297. .. admonition:: Estimating memory usage
    
  298. 
    
  299.     The minimum memory requirement of scrypt_ is::
    
  300. 
    
  301.         work_factor * 2 * block_size * 64
    
  302. 
    
  303.     so you may need to tweak ``maxmem`` when changing the ``work_factor`` or
    
  304.     ``block_size`` values.
    
  305. 
    
  306. .. _password-upgrades:
    
  307. 
    
  308. Password upgrading
    
  309. ------------------
    
  310. 
    
  311. When users log in, if their passwords are stored with anything other than
    
  312. the preferred algorithm, Django will automatically upgrade the algorithm
    
  313. to the preferred one. This means that old installs of Django will get
    
  314. automatically more secure as users log in, and it also means that you
    
  315. can switch to new (and better) storage algorithms as they get invented.
    
  316. 
    
  317. However, Django can only upgrade passwords that use algorithms mentioned in
    
  318. :setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
    
  319. sure never to *remove* entries from this list. If you do, users using
    
  320. unmentioned algorithms won't be able to upgrade. Hashed passwords will be
    
  321. updated when increasing (or decreasing) the number of PBKDF2 iterations, bcrypt
    
  322. rounds, or argon2 attributes.
    
  323. 
    
  324. Be aware that if all the passwords in your database aren't encoded in the
    
  325. default hasher's algorithm, you may be vulnerable to a user enumeration timing
    
  326. attack due to a difference between the duration of a login request for a user
    
  327. with a password encoded in a non-default algorithm and the duration of a login
    
  328. request for a nonexistent user (which runs the default hasher). You may be able
    
  329. to mitigate this by :ref:`upgrading older password hashes
    
  330. <wrapping-password-hashers>`.
    
  331. 
    
  332. .. _wrapping-password-hashers:
    
  333. 
    
  334. Password upgrading without requiring a login
    
  335. --------------------------------------------
    
  336. 
    
  337. If you have an existing database with an older, weak hash such as MD5 or SHA1,
    
  338. you might want to upgrade those hashes yourself instead of waiting for the
    
  339. upgrade to happen when a user logs in (which may never happen if a user doesn't
    
  340. return to your site). In this case, you can use a "wrapped" password hasher.
    
  341. 
    
  342. For this example, we'll migrate a collection of SHA1 hashes to use
    
  343. PBKDF2(SHA1(password)) and add the corresponding password hasher for checking
    
  344. if a user entered the correct password on login. We assume we're using the
    
  345. built-in ``User`` model and that our project has an ``accounts`` app. You can
    
  346. modify the pattern to work with any algorithm or with a custom user model.
    
  347. 
    
  348. First, we'll add the custom hasher:
    
  349. 
    
  350. .. code-block:: python
    
  351.     :caption: ``accounts/hashers.py``
    
  352. 
    
  353.     from django.contrib.auth.hashers import (
    
  354.         PBKDF2PasswordHasher, SHA1PasswordHasher,
    
  355.     )
    
  356. 
    
  357. 
    
  358.     class PBKDF2WrappedSHA1PasswordHasher(PBKDF2PasswordHasher):
    
  359.         algorithm = 'pbkdf2_wrapped_sha1'
    
  360. 
    
  361.         def encode_sha1_hash(self, sha1_hash, salt, iterations=None):
    
  362.             return super().encode(sha1_hash, salt, iterations)
    
  363. 
    
  364.         def encode(self, password, salt, iterations=None):
    
  365.             _, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)
    
  366.             return self.encode_sha1_hash(sha1_hash, salt, iterations)
    
  367. 
    
  368. The data migration might look something like:
    
  369. 
    
  370. .. code-block:: python
    
  371.     :caption: ``accounts/migrations/0002_migrate_sha1_passwords.py``
    
  372. 
    
  373.     from django.db import migrations
    
  374. 
    
  375.     from ..hashers import PBKDF2WrappedSHA1PasswordHasher
    
  376. 
    
  377. 
    
  378.     def forwards_func(apps, schema_editor):
    
  379.         User = apps.get_model('auth', 'User')
    
  380.         users = User.objects.filter(password__startswith='sha1$')
    
  381.         hasher = PBKDF2WrappedSHA1PasswordHasher()
    
  382.         for user in users:
    
  383.             algorithm, salt, sha1_hash = user.password.split('$', 2)
    
  384.             user.password = hasher.encode_sha1_hash(sha1_hash, salt)
    
  385.             user.save(update_fields=['password'])
    
  386. 
    
  387. 
    
  388.     class Migration(migrations.Migration):
    
  389. 
    
  390.         dependencies = [
    
  391.             ('accounts', '0001_initial'),
    
  392.             # replace this with the latest migration in contrib.auth
    
  393.             ('auth', '####_migration_name'),
    
  394.         ]
    
  395. 
    
  396.         operations = [
    
  397.             migrations.RunPython(forwards_func),
    
  398.         ]
    
  399. 
    
  400. Be aware that this migration will take on the order of several minutes for
    
  401. several thousand users, depending on the speed of your hardware.
    
  402. 
    
  403. Finally, we'll add a :setting:`PASSWORD_HASHERS` setting:
    
  404. 
    
  405. .. code-block:: python
    
  406.     :caption: ``mysite/settings.py``
    
  407. 
    
  408.     PASSWORD_HASHERS = [
    
  409.         'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  410.         'accounts.hashers.PBKDF2WrappedSHA1PasswordHasher',
    
  411.     ]
    
  412. 
    
  413. Include any other hashers that your site uses in this list.
    
  414. 
    
  415. .. _sha1: https://en.wikipedia.org/wiki/SHA1
    
  416. .. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2
    
  417. .. _nist: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
    
  418. .. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt
    
  419. .. _`bcrypt library`: https://pypi.org/project/bcrypt/
    
  420. .. _`argon2-cffi library`: https://pypi.org/project/argon2-cffi/
    
  421. .. _argon2: https://en.wikipedia.org/wiki/Argon2
    
  422. .. _scrypt: https://en.wikipedia.org/wiki/Scrypt
    
  423. .. _`Password Hashing Competition`: https://www.password-hashing.net/
    
  424. 
    
  425. .. _auth-included-hashers:
    
  426. 
    
  427. Included hashers
    
  428. ----------------
    
  429. 
    
  430. The full list of hashers included in Django is::
    
  431. 
    
  432.     [
    
  433.         'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    
  434.         'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    
  435.         'django.contrib.auth.hashers.Argon2PasswordHasher',
    
  436.         'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    
  437.         'django.contrib.auth.hashers.BCryptPasswordHasher',
    
  438.         'django.contrib.auth.hashers.ScryptPasswordHasher',
    
  439.         'django.contrib.auth.hashers.SHA1PasswordHasher',
    
  440.         'django.contrib.auth.hashers.MD5PasswordHasher',
    
  441.         'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
    
  442.         'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
    
  443.     ]
    
  444. 
    
  445. The corresponding algorithm names are:
    
  446. 
    
  447. * ``pbkdf2_sha256``
    
  448. * ``pbkdf2_sha1``
    
  449. * ``argon2``
    
  450. * ``bcrypt_sha256``
    
  451. * ``bcrypt``
    
  452. * ``scrypt``
    
  453. * ``sha1``
    
  454. * ``md5``
    
  455. * ``unsalted_sha1``
    
  456. * ``unsalted_md5``
    
  457. 
    
  458. .. _write-your-own-password-hasher:
    
  459. 
    
  460. Writing your own hasher
    
  461. -----------------------
    
  462. 
    
  463. If you write your own password hasher that contains a work factor such as a
    
  464. number of iterations, you should implement a
    
  465. ``harden_runtime(self, password, encoded)`` method to bridge the runtime gap
    
  466. between the work factor supplied in the ``encoded`` password and the default
    
  467. work factor of the hasher. This prevents a user enumeration timing attack due
    
  468. to  difference between a login request for a user with a password encoded in an
    
  469. older number of iterations and a nonexistent user (which runs the default
    
  470. hasher's default number of iterations).
    
  471. 
    
  472. Taking PBKDF2 as example, if ``encoded`` contains 20,000 iterations and the
    
  473. hasher's default ``iterations`` is 30,000, the method should run ``password``
    
  474. through another 10,000 iterations of PBKDF2.
    
  475. 
    
  476. If your hasher doesn't have a work factor, implement the method as a no-op
    
  477. (``pass``).
    
  478. 
    
  479. Manually managing a user's password
    
  480. ===================================
    
  481. 
    
  482. .. module:: django.contrib.auth.hashers
    
  483. 
    
  484. The :mod:`django.contrib.auth.hashers` module provides a set of functions
    
  485. to create and validate hashed passwords. You can use them independently
    
  486. from the ``User`` model.
    
  487. 
    
  488. .. function:: check_password(password, encoded, setter=None, preferred="default")
    
  489. 
    
  490.     If you'd like to manually authenticate a user by comparing a plain-text
    
  491.     password to the hashed password in the database, use the convenience
    
  492.     function :func:`check_password`. It takes two mandatory arguments: the
    
  493.     plain-text password to check, and the full value of a user's ``password``
    
  494.     field in the database to check against. It returns ``True`` if they match,
    
  495.     ``False`` otherwise. Optionally, you can pass a callable ``setter`` that
    
  496.     takes the password and will be called when you need to regenerate it. You
    
  497.     can also pass ``preferred`` to change a hashing algorithm if you don't want
    
  498.     to use the default (first entry of ``PASSWORD_HASHERS`` setting). See
    
  499.     :ref:`auth-included-hashers` for the algorithm name of each hasher.
    
  500. 
    
  501. .. function:: make_password(password, salt=None, hasher='default')
    
  502. 
    
  503.     Creates a hashed password in the format used by this application. It takes
    
  504.     one mandatory argument: the password in plain-text (string or bytes).
    
  505.     Optionally, you can provide a salt and a hashing algorithm to use, if you
    
  506.     don't want to use the defaults (first entry of ``PASSWORD_HASHERS``
    
  507.     setting). See :ref:`auth-included-hashers` for the algorithm name of each
    
  508.     hasher. If the password argument is ``None``, an unusable password is
    
  509.     returned (one that will never be accepted by :func:`check_password`).
    
  510. 
    
  511. .. function:: is_password_usable(encoded_password)
    
  512. 
    
  513.     Returns ``False`` if the password is a result of
    
  514.     :meth:`.User.set_unusable_password`.
    
  515. 
    
  516. .. _password-validation:
    
  517. 
    
  518. Password validation
    
  519. ===================
    
  520. 
    
  521. .. module:: django.contrib.auth.password_validation
    
  522. 
    
  523. Users often choose poor passwords. To help mitigate this problem, Django
    
  524. offers pluggable password validation. You can configure multiple password
    
  525. validators at the same time. A few validators are included in Django, but you
    
  526. can write your own as well.
    
  527. 
    
  528. Each password validator must provide a help text to explain the requirements to
    
  529. the user, validate a given password and return an error message if it does not
    
  530. meet the requirements, and optionally receive passwords that have been set.
    
  531. Validators can also have optional settings to fine tune their behavior.
    
  532. 
    
  533. Validation is controlled by the :setting:`AUTH_PASSWORD_VALIDATORS` setting.
    
  534. The default for the setting is an empty list, which means no validators are
    
  535. applied. In new projects created with the default :djadmin:`startproject`
    
  536. template, a set of validators is enabled by default.
    
  537. 
    
  538. By default, validators are used in the forms to reset or change passwords and
    
  539. in the :djadmin:`createsuperuser` and :djadmin:`changepassword` management
    
  540. commands. Validators aren't applied at the model level, for example in
    
  541. ``User.objects.create_user()`` and ``create_superuser()``, because we assume
    
  542. that developers, not users, interact with Django at that level and also because
    
  543. model validation doesn't automatically run as part of creating models.
    
  544. 
    
  545. .. note::
    
  546. 
    
  547.     Password validation can prevent the use of many types of weak passwords.
    
  548.     However, the fact that a password passes all the validators doesn't
    
  549.     guarantee that it is a strong password. There are many factors that can
    
  550.     weaken a password that are not detectable by even the most advanced
    
  551.     password validators.
    
  552. 
    
  553. Enabling password validation
    
  554. ----------------------------
    
  555. 
    
  556. Password validation is configured in the
    
  557. :setting:`AUTH_PASSWORD_VALIDATORS` setting::
    
  558. 
    
  559.     AUTH_PASSWORD_VALIDATORS = [
    
  560.         {
    
  561.             'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    
  562.         },
    
  563.         {
    
  564.             'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    
  565.             'OPTIONS': {
    
  566.                 'min_length': 9,
    
  567.             }
    
  568.         },
    
  569.         {
    
  570.             'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    
  571.         },
    
  572.         {
    
  573.             'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    
  574.         },
    
  575.     ]
    
  576. 
    
  577. This example enables all four included validators:
    
  578. 
    
  579. * ``UserAttributeSimilarityValidator``, which checks the similarity between
    
  580.   the password and a set of attributes of the user.
    
  581. * ``MinimumLengthValidator``, which checks whether the password meets a minimum
    
  582.   length. This validator is configured with a custom option: it now requires
    
  583.   the minimum length to be nine characters, instead of the default eight.
    
  584. * ``CommonPasswordValidator``, which checks whether the password occurs in a
    
  585.   list of common passwords. By default, it compares to an included list of
    
  586.   20,000 common passwords.
    
  587. * ``NumericPasswordValidator``, which checks whether the password isn't
    
  588.   entirely numeric.
    
  589. 
    
  590. For ``UserAttributeSimilarityValidator`` and ``CommonPasswordValidator``,
    
  591. we're using the default settings in this example. ``NumericPasswordValidator``
    
  592. has no settings.
    
  593. 
    
  594. The help texts and any errors from password validators are always returned in
    
  595. the order they are listed in :setting:`AUTH_PASSWORD_VALIDATORS`.
    
  596. 
    
  597. Included validators
    
  598. -------------------
    
  599. 
    
  600. Django includes four validators:
    
  601. 
    
  602. .. class:: MinimumLengthValidator(min_length=8)
    
  603. 
    
  604.     Validates that the password is of a minimum length.
    
  605.     The minimum length can be customized with the ``min_length`` parameter.
    
  606. 
    
  607. .. class:: UserAttributeSimilarityValidator(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)
    
  608. 
    
  609.     Validates that the password is sufficiently different from certain
    
  610.     attributes of the user.
    
  611. 
    
  612.     The ``user_attributes`` parameter should be an iterable of names of user
    
  613.     attributes to compare to. If this argument is not provided, the default
    
  614.     is used: ``'username', 'first_name', 'last_name', 'email'``.
    
  615.     Attributes that don't exist are ignored.
    
  616. 
    
  617.     The maximum allowed similarity of passwords can be set on a scale of 0.1
    
  618.     to 1.0 with the ``max_similarity`` parameter. This is compared to the
    
  619.     result of :meth:`difflib.SequenceMatcher.quick_ratio`. A value of 0.1
    
  620.     rejects passwords unless they are substantially different from the
    
  621.     ``user_attributes``, whereas a value of 1.0 rejects only passwords that are
    
  622.     identical to an attribute's value.
    
  623. 
    
  624.     .. versionchanged:: 2.2.26
    
  625. 
    
  626.         The ``max_similarity`` parameter was limited to a minimum value of 0.1.
    
  627. 
    
  628. .. class:: CommonPasswordValidator(password_list_path=DEFAULT_PASSWORD_LIST_PATH)
    
  629. 
    
  630.     Validates that the password is not a common password. This converts the
    
  631.     password to lowercase (to do a case-insensitive comparison) and checks it
    
  632.     against a list of 20,000 common password created by `Royce Williams
    
  633.     <https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7>`_.
    
  634. 
    
  635.     The ``password_list_path`` can be set to the path of a custom file of
    
  636.     common passwords. This file should contain one lowercase password per line
    
  637.     and may be plain text or gzipped.
    
  638. 
    
  639. .. class:: NumericPasswordValidator()
    
  640. 
    
  641.     Validate that the password is not entirely numeric.
    
  642. 
    
  643. Integrating validation
    
  644. ----------------------
    
  645. 
    
  646. There are a few functions in ``django.contrib.auth.password_validation`` that
    
  647. you can call from your own forms or other code to integrate password
    
  648. validation. This can be useful if you use custom forms for password setting,
    
  649. or if you have API calls that allow passwords to be set, for example.
    
  650. 
    
  651. .. function:: validate_password(password, user=None, password_validators=None)
    
  652. 
    
  653.     Validates a password. If all validators find the password valid, returns
    
  654.     ``None``. If one or more validators reject the password, raises a
    
  655.     :exc:`~django.core.exceptions.ValidationError` with all the error messages
    
  656.     from the validators.
    
  657. 
    
  658.     The ``user`` object is optional: if it's not provided, some validators may
    
  659.     not be able to perform any validation and will accept any password.
    
  660. 
    
  661. .. function:: password_changed(password, user=None, password_validators=None)
    
  662. 
    
  663.     Informs all validators that the password has been changed. This can be used
    
  664.     by validators such as one that prevents password reuse. This should be
    
  665.     called once the password has been successfully changed.
    
  666. 
    
  667.     For subclasses of :class:`~django.contrib.auth.models.AbstractBaseUser`,
    
  668.     the password field will be marked as "dirty" when calling
    
  669.     :meth:`~django.contrib.auth.models.AbstractBaseUser.set_password` which
    
  670.     triggers a call to ``password_changed()`` after the user is saved.
    
  671. 
    
  672. .. function:: password_validators_help_texts(password_validators=None)
    
  673. 
    
  674.     Returns a list of the help texts of all validators. These explain the
    
  675.     password requirements to the user.
    
  676. 
    
  677. .. function:: password_validators_help_text_html(password_validators=None)
    
  678. 
    
  679.     Returns an HTML string with all help texts in an ``<ul>``. This is
    
  680.     helpful when adding password validation to forms, as you can pass the
    
  681.     output directly to the ``help_text`` parameter of a form field.
    
  682. 
    
  683. .. function:: get_password_validators(validator_config)
    
  684. 
    
  685.     Returns a set of validator objects based on the ``validator_config``
    
  686.     parameter. By default, all functions use the validators defined in
    
  687.     :setting:`AUTH_PASSWORD_VALIDATORS`, but by calling this function with an
    
  688.     alternate set of validators and then passing the result into the
    
  689.     ``password_validators`` parameter of the other functions, your custom set
    
  690.     of validators will be used instead. This is useful when you have a typical
    
  691.     set of validators to use for most scenarios, but also have a special
    
  692.     situation that requires a custom set. If you always use the same set
    
  693.     of validators, there is no need to use this function, as the configuration
    
  694.     from :setting:`AUTH_PASSWORD_VALIDATORS` is used by default.
    
  695. 
    
  696.     The structure of ``validator_config`` is identical to the
    
  697.     structure of :setting:`AUTH_PASSWORD_VALIDATORS`. The return value of
    
  698.     this function can be passed into the ``password_validators`` parameter
    
  699.     of the functions listed above.
    
  700. 
    
  701. Note that where the password is passed to one of these functions, this should
    
  702. always be the clear text password - not a hashed password.
    
  703. 
    
  704. Writing your own validator
    
  705. --------------------------
    
  706. 
    
  707. If Django's built-in validators are not sufficient, you can write your own
    
  708. password validators. Validators have a fairly small interface. They must
    
  709. implement two methods:
    
  710. 
    
  711. * ``validate(self, password, user=None)``: validate a password. Return
    
  712.   ``None`` if the password is valid, or raise a
    
  713.   :exc:`~django.core.exceptions.ValidationError` with an error message if the
    
  714.   password is not valid. You must be able to deal with ``user`` being
    
  715.   ``None`` - if that means your validator can't run, return ``None`` for no
    
  716.   error.
    
  717. * ``get_help_text()``: provide a help text to explain the requirements to
    
  718.   the user.
    
  719. 
    
  720. Any items in the ``OPTIONS`` in :setting:`AUTH_PASSWORD_VALIDATORS` for your
    
  721. validator will be passed to the constructor. All constructor arguments should
    
  722. have a default value.
    
  723. 
    
  724. Here's a basic example of a validator, with one optional setting::
    
  725. 
    
  726.     from django.core.exceptions import ValidationError
    
  727.     from django.utils.translation import gettext as _
    
  728. 
    
  729.     class MinimumLengthValidator:
    
  730.         def __init__(self, min_length=8):
    
  731.             self.min_length = min_length
    
  732. 
    
  733.         def validate(self, password, user=None):
    
  734.             if len(password) < self.min_length:
    
  735.                 raise ValidationError(
    
  736.                     _("This password must contain at least %(min_length)d characters."),
    
  737.                     code='password_too_short',
    
  738.                     params={'min_length': self.min_length},
    
  739.                 )
    
  740. 
    
  741.         def get_help_text(self):
    
  742.             return _(
    
  743.                 "Your password must contain at least %(min_length)d characters."
    
  744.                 % {'min_length': self.min_length}
    
  745.             )
    
  746. 
    
  747. You can also implement ``password_changed(password, user=None``), which will
    
  748. be called after a successful password change. That can be used to prevent
    
  749. password reuse, for example. However, if you decide to store a user's previous
    
  750. passwords, you should never do so in clear text.