passwords.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. =============================
  2. Password management in Django
  3. =============================
  4. Password management is something that should generally not be reinvented
  5. unnecessarily, and Django endeavors to provide a secure and flexible set of
  6. tools for managing user passwords. This document describes how Django stores
  7. passwords, how the storage hashing can be configured, and some utilities to
  8. work with hashed passwords.
  9. .. seealso::
  10. Even though users may use strong passwords, attackers might be able to
  11. eavesdrop on their connections. Use :ref:`HTTPS
  12. <security-recommendation-ssl>` to avoid sending passwords (or any other
  13. sensitive data) over plain HTTP connections because they will be vulnerable
  14. to password sniffing.
  15. .. _auth_password_storage:
  16. How Django stores passwords
  17. ===========================
  18. Django provides a flexible password storage system and uses PBKDF2 by default.
  19. The :attr:`~django.contrib.auth.models.User.password` attribute of a
  20. :class:`~django.contrib.auth.models.User` object is a string in this format::
  21. <algorithm>$<iterations>$<salt>$<hash>
  22. Those are the components used for storing a User's password, separated by the
  23. dollar-sign character and consist of: the hashing algorithm, the number of
  24. algorithm iterations (work factor), the random salt, and the resulting password
  25. hash. The algorithm is one of a number of one-way hashing or password storage
  26. algorithms Django can use; see below. Iterations describe the number of times
  27. the algorithm is run over the hash. Salt is the random seed used and the hash
  28. is the result of the one-way function.
  29. By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
  30. password stretching mechanism recommended by NIST_. This should be
  31. sufficient for most users: it's quite secure, requiring massive
  32. amounts of computing time to break.
  33. However, depending on your requirements, you may choose a different
  34. algorithm, or even use a custom algorithm to match your specific
  35. security situation. Again, most users shouldn't need to do this -- if
  36. you're not sure, you probably don't. If you do, please read on:
  37. Django chooses the algorithm to use by consulting the
  38. :setting:`PASSWORD_HASHERS` setting. This is a list of hashing algorithm
  39. classes that this Django installation supports. The first entry in this list
  40. (that is, ``settings.PASSWORD_HASHERS[0]``) will be used to store passwords,
  41. and all the other entries are valid hashers that can be used to check existing
  42. passwords. This means that if you want to use a different algorithm, you'll
  43. need to modify :setting:`PASSWORD_HASHERS` to list your preferred algorithm
  44. first in the list.
  45. The default for :setting:`PASSWORD_HASHERS` is::
  46. PASSWORD_HASHERS = [
  47. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  48. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  49. 'django.contrib.auth.hashers.Argon2PasswordHasher',
  50. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  51. ]
  52. This means that Django will use PBKDF2_ to store all passwords but will support
  53. checking passwords stored with PBKDF2SHA1, argon2_, and bcrypt_.
  54. The next few sections describe a couple of common ways advanced users may want
  55. to modify this setting.
  56. .. _argon2_usage:
  57. Using Argon2 with Django
  58. ------------------------
  59. Argon2_ is the winner of the 2015 `Password Hashing Competition`_, a community
  60. organized open competition to select a next generation hashing algorithm. It's
  61. designed not to be easier to compute on custom hardware than it is to compute
  62. on an ordinary CPU.
  63. Argon2_ is not the default for Django because it requires a third-party
  64. library. The Password Hashing Competition panel, however, recommends immediate
  65. use of Argon2 rather than the other algorithms supported by Django.
  66. To use Argon2 as your default storage algorithm, do the following:
  67. 1. Install the `argon2-cffi library`_. This can be done by running ``pip
  68. install django[argon2]``, which is equivalent to ``pip install argon2-cffi``
  69. (along with any version requirement from Django's ``setup.py``).
  70. 2. Modify :setting:`PASSWORD_HASHERS` to list ``Argon2PasswordHasher`` first.
  71. That is, in your settings file, you'd put::
  72. PASSWORD_HASHERS = [
  73. 'django.contrib.auth.hashers.Argon2PasswordHasher',
  74. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  75. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  76. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  77. ]
  78. Keep and/or add any entries in this list if you need Django to :ref:`upgrade
  79. passwords <password-upgrades>`.
  80. .. _bcrypt_usage:
  81. Using ``bcrypt`` with Django
  82. ----------------------------
  83. Bcrypt_ is a popular password storage algorithm that's specifically designed
  84. for long-term password storage. It's not the default used by Django since it
  85. requires the use of third-party libraries, but since many people may want to
  86. use it Django supports bcrypt with minimal effort.
  87. To use Bcrypt as your default storage algorithm, do the following:
  88. 1. Install the `bcrypt library`_. This can be done by running ``pip install
  89. django[bcrypt]``, which is equivalent to ``pip install bcrypt`` (along with
  90. any version requirement from Django's ``setup.py``).
  91. 2. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptSHA256PasswordHasher``
  92. first. That is, in your settings file, you'd put::
  93. PASSWORD_HASHERS = [
  94. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  95. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  96. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  97. 'django.contrib.auth.hashers.Argon2PasswordHasher',
  98. ]
  99. Keep and/or add any entries in this list if you need Django to :ref:`upgrade
  100. passwords <password-upgrades>`.
  101. That's it -- now your Django install will use Bcrypt as the default storage
  102. algorithm.
  103. .. _increasing-password-algorithm-work-factor:
  104. Increasing the work factor
  105. --------------------------
  106. PBKDF2 and bcrypt
  107. ~~~~~~~~~~~~~~~~~
  108. The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
  109. hashing. This deliberately slows down attackers, making attacks against hashed
  110. passwords harder. However, as computing power increases, the number of
  111. iterations needs to be increased. We've chosen a reasonable default (and will
  112. increase it with each release of Django), but you may wish to tune it up or
  113. down, depending on your security needs and available processing power. To do so,
  114. you'll subclass the appropriate algorithm and override the ``iterations``
  115. parameters. For example, to increase the number of iterations used by the
  116. default PBKDF2 algorithm:
  117. 1. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
  118. from django.contrib.auth.hashers import PBKDF2PasswordHasher
  119. class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
  120. """
  121. A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
  122. """
  123. iterations = PBKDF2PasswordHasher.iterations * 100
  124. Save this somewhere in your project. For example, you might put this in
  125. a file like ``myproject/hashers.py``.
  126. 2. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
  127. PASSWORD_HASHERS = [
  128. 'myproject.hashers.MyPBKDF2PasswordHasher',
  129. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  130. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  131. 'django.contrib.auth.hashers.Argon2PasswordHasher',
  132. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  133. ]
  134. That's it -- now your Django install will use more iterations when it
  135. stores passwords using PBKDF2.
  136. Argon2
  137. ~~~~~~
  138. Argon2 has three attributes that can be customized:
  139. #. ``time_cost`` controls the number of iterations within the hash.
  140. #. ``memory_cost`` controls the size of memory that must be used during the
  141. computation of the hash.
  142. #. ``parallelism`` controls how many CPUs the computation of the hash can be
  143. parallelized on.
  144. The default values of these attributes are probably fine for you. If you
  145. determine that the password hash is too fast or too slow, you can tweak it as
  146. follows:
  147. #. Choose ``parallelism`` to be the number of threads you can
  148. spare computing the hash.
  149. #. Choose ``memory_cost`` to be the KiB of memory you can spare.
  150. #. Adjust ``time_cost`` and measure the time hashing a password takes.
  151. Pick a ``time_cost`` that takes an acceptable time for you.
  152. If ``time_cost`` set to 1 is unacceptably slow, lower ``memory_cost``.
  153. .. admonition:: ``memory_cost`` interpretation
  154. The argon2 command-line utility and some other libraries interpret the
  155. ``memory_cost`` parameter differently from the value that Django uses. The
  156. conversion is given by ``memory_cost == 2 ** memory_cost_commandline``.
  157. .. _password-upgrades:
  158. Password upgrading
  159. ------------------
  160. When users log in, if their passwords are stored with anything other than
  161. the preferred algorithm, Django will automatically upgrade the algorithm
  162. to the preferred one. This means that old installs of Django will get
  163. automatically more secure as users log in, and it also means that you
  164. can switch to new (and better) storage algorithms as they get invented.
  165. However, Django can only upgrade passwords that use algorithms mentioned in
  166. :setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
  167. sure never to *remove* entries from this list. If you do, users using
  168. unmentioned algorithms won't be able to upgrade. Hashed passwords will be
  169. updated when increasing (or decreasing) the number of PBKDF2 iterations or
  170. bcrypt rounds.
  171. Be aware that if all the passwords in your database aren't encoded in the
  172. default hasher's algorithm, you may be vulnerable to a user enumeration timing
  173. attack due to a difference between the duration of a login request for a user
  174. with a password encoded in a non-default algorithm and the duration of a login
  175. request for a nonexistent user (which runs the default hasher). You may be able
  176. to mitigate this by :ref:`upgrading older password hashes
  177. <wrapping-password-hashers>`.
  178. .. _wrapping-password-hashers:
  179. Password upgrading without requiring a login
  180. --------------------------------------------
  181. If you have an existing database with an older, weak hash such as MD5 or SHA1,
  182. you might want to upgrade those hashes yourself instead of waiting for the
  183. upgrade to happen when a user logs in (which may never happen if a user doesn't
  184. return to your site). In this case, you can use a "wrapped" password hasher.
  185. For this example, we'll migrate a collection of SHA1 hashes to use
  186. PBKDF2(SHA1(password)) and add the corresponding password hasher for checking
  187. if a user entered the correct password on login. We assume we're using the
  188. built-in ``User`` model and that our project has an ``accounts`` app. You can
  189. modify the pattern to work with any algorithm or with a custom user model.
  190. First, we'll add the custom hasher:
  191. .. snippet::
  192. :filename: accounts/hashers.py
  193. from django.contrib.auth.hashers import (
  194. PBKDF2PasswordHasher, SHA1PasswordHasher,
  195. )
  196. class PBKDF2WrappedSHA1PasswordHasher(PBKDF2PasswordHasher):
  197. algorithm = 'pbkdf2_wrapped_sha1'
  198. def encode_sha1_hash(self, sha1_hash, salt, iterations=None):
  199. return super().encode(sha1_hash, salt, iterations)
  200. def encode(self, password, salt, iterations=None):
  201. _, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)
  202. return self.encode_sha1_hash(sha1_hash, salt, iterations)
  203. The data migration might look something like:
  204. .. snippet::
  205. :filename: accounts/migrations/0002_migrate_sha1_passwords.py
  206. from django.db import migrations
  207. from ..hashers import PBKDF2WrappedSHA1PasswordHasher
  208. def forwards_func(apps, schema_editor):
  209. User = apps.get_model('auth', 'User')
  210. users = User.objects.filter(password__startswith='sha1$')
  211. hasher = PBKDF2WrappedSHA1PasswordHasher()
  212. for user in users:
  213. algorithm, salt, sha1_hash = user.password.split('$', 2)
  214. user.password = hasher.encode_sha1_hash(sha1_hash, salt)
  215. user.save(update_fields=['password'])
  216. class Migration(migrations.Migration):
  217. dependencies = [
  218. ('accounts', '0001_initial'),
  219. # replace this with the latest migration in contrib.auth
  220. ('auth', '####_migration_name'),
  221. ]
  222. operations = [
  223. migrations.RunPython(forwards_func),
  224. ]
  225. Be aware that this migration will take on the order of several minutes for
  226. several thousand users, depending on the speed of your hardware.
  227. Finally, we'll add a :setting:`PASSWORD_HASHERS` setting:
  228. .. snippet::
  229. :filename: mysite/settings.py
  230. PASSWORD_HASHERS = [
  231. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  232. 'accounts.hashers.PBKDF2WrappedSHA1PasswordHasher',
  233. ]
  234. Include any other hashers that your site uses in this list.
  235. .. _sha1: https://en.wikipedia.org/wiki/SHA1
  236. .. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2
  237. .. _nist: https://dx.doi.org/10.6028/NIST.SP.800-132
  238. .. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt
  239. .. _`bcrypt library`: https://pypi.python.org/pypi/bcrypt/
  240. .. _`argon2-cffi library`: https://pypi.python.org/pypi/argon2_cffi/
  241. .. _argon2: https://en.wikipedia.org/wiki/Argon2
  242. .. _`Password Hashing Competition`: https://password-hashing.net
  243. .. _auth-included-hashers:
  244. Included hashers
  245. ----------------
  246. The full list of hashers included in Django is::
  247. [
  248. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  249. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  250. 'django.contrib.auth.hashers.Argon2PasswordHasher',
  251. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
  252. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  253. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  254. 'django.contrib.auth.hashers.MD5PasswordHasher',
  255. 'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
  256. 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
  257. 'django.contrib.auth.hashers.CryptPasswordHasher',
  258. ]
  259. The corresponding algorithm names are:
  260. * ``pbkdf2_sha256``
  261. * ``pbkdf2_sha1``
  262. * ``argon2``
  263. * ``bcrypt_sha256``
  264. * ``bcrypt``
  265. * ``sha1``
  266. * ``md5``
  267. * ``unsalted_sha1``
  268. * ``unsalted_md5``
  269. * ``crypt``
  270. .. _write-your-own-password-hasher:
  271. Writing your own hasher
  272. -----------------------
  273. If you write your own password hasher that contains a work factor such as a
  274. number of iterations, you should implement a
  275. ``harden_runtime(self, password, encoded)`` method to bridge the runtime gap
  276. between the work factor supplied in the ``encoded`` password and the default
  277. work factor of the hasher. This prevents a user enumeration timing attack due
  278. to difference between a login request for a user with a password encoded in an
  279. older number of iterations and a nonexistent user (which runs the default
  280. hasher's default number of iterations).
  281. Taking PBKDF2 as example, if ``encoded`` contains 20,000 iterations and the
  282. hasher's default ``iterations`` is 30,000, the method should run ``password``
  283. through another 10,000 iterations of PBKDF2.
  284. If your hasher doesn't have a work factor, implement the method as a no-op
  285. (``pass``).
  286. Manually managing a user's password
  287. ===================================
  288. .. module:: django.contrib.auth.hashers
  289. The :mod:`django.contrib.auth.hashers` module provides a set of functions
  290. to create and validate hashed password. You can use them independently
  291. from the ``User`` model.
  292. .. function:: check_password(password, encoded)
  293. If you'd like to manually authenticate a user by comparing a plain-text
  294. password to the hashed password in the database, use the convenience
  295. function :func:`check_password`. It takes two arguments: the plain-text
  296. password to check, and the full value of a user's ``password`` field in the
  297. database to check against, and returns ``True`` if they match, ``False``
  298. otherwise.
  299. .. function:: make_password(password, salt=None, hasher='default')
  300. Creates a hashed password in the format used by this application. It takes
  301. one mandatory argument: the password in plain-text. Optionally, you can
  302. provide a salt and a hashing algorithm to use, if you don't want to use the
  303. defaults (first entry of ``PASSWORD_HASHERS`` setting). See
  304. :ref:`auth-included-hashers` for the algorithm name of each hasher. If the
  305. password argument is ``None``, an unusable password is returned (a one that
  306. will be never accepted by :func:`check_password`).
  307. .. function:: is_password_usable(encoded_password)
  308. Returns ``False`` if the password is a result of
  309. :meth:`.User.set_unusable_password`.
  310. .. versionchanged:: 2.1
  311. In older versions, this also returns ``False`` if the password is
  312. ``None`` or an empty string, or if the password uses a hasher that's
  313. not in the :setting:`PASSWORD_HASHERS` setting. That behavior is
  314. considered a bug as it prevents users with such passwords from
  315. requesting a password reset.
  316. .. _password-validation:
  317. Password validation
  318. ===================
  319. .. module:: django.contrib.auth.password_validation
  320. Users often choose poor passwords. To help mitigate this problem, Django
  321. offers pluggable password validation. You can configure multiple password
  322. validators at the same time. A few validators are included in Django, but it's
  323. simple to write your own as well.
  324. Each password validator must provide a help text to explain the requirements to
  325. the user, validate a given password and return an error message if it does not
  326. meet the requirements, and optionally receive passwords that have been set.
  327. Validators can also have optional settings to fine tune their behavior.
  328. Validation is controlled by the :setting:`AUTH_PASSWORD_VALIDATORS` setting.
  329. The default for the setting is an empty list, which means no validators are
  330. applied. In new projects created with the default :djadmin:`startproject`
  331. template, a simple set of validators is enabled.
  332. By default, validators are used in the forms to reset or change passwords and
  333. in the :djadmin:`createsuperuser` and :djadmin:`changepassword` management
  334. commands. Validators aren't applied at the model level, for example in
  335. ``User.objects.create_user()`` and ``create_superuser()``, because we assume
  336. that developers, not users, interact with Django at that level and also because
  337. model validation doesn't automatically run as part of creating models.
  338. .. note::
  339. Password validation can prevent the use of many types of weak passwords.
  340. However, the fact that a password passes all the validators doesn't
  341. guarantee that it is a strong password. There are many factors that can
  342. weaken a password that are not detectable by even the most advanced
  343. password validators.
  344. Enabling password validation
  345. ----------------------------
  346. Password validation is configured in the
  347. :setting:`AUTH_PASSWORD_VALIDATORS` setting::
  348. AUTH_PASSWORD_VALIDATORS = [
  349. {
  350. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  351. },
  352. {
  353. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  354. 'OPTIONS': {
  355. 'min_length': 9,
  356. }
  357. },
  358. {
  359. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  360. },
  361. {
  362. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  363. },
  364. ]
  365. This example enables all four included validators:
  366. * ``UserAttributeSimilarityValidator``, which checks the similarity between
  367. the password and a set of attributes of the user.
  368. * ``MinimumLengthValidator``, which simply checks whether the password meets a
  369. minimum length. This validator is configured with a custom option: it now
  370. requires the minimum length to be nine characters, instead of the default
  371. eight.
  372. * ``CommonPasswordValidator``, which checks whether the password occurs in a
  373. list of common passwords. By default, it compares to an included list of
  374. 1000 common passwords.
  375. * ``NumericPasswordValidator``, which checks whether the password isn't
  376. entirely numeric.
  377. For ``UserAttributeSimilarityValidator`` and ``CommonPasswordValidator``,
  378. we're simply using the default settings in this example.
  379. ``NumericPasswordValidator`` has no settings.
  380. The help texts and any errors from password validators are always returned in
  381. the order they are listed in :setting:`AUTH_PASSWORD_VALIDATORS`.
  382. Included validators
  383. -------------------
  384. Django includes four validators:
  385. .. class:: MinimumLengthValidator(min_length=8)
  386. Validates whether the password meets a minimum length.
  387. The minimum length can be customized with the ``min_length`` parameter.
  388. .. class:: UserAttributeSimilarityValidator(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)
  389. Validates whether the password is sufficiently different from certain
  390. attributes of the user.
  391. The ``user_attributes`` parameter should be an iterable of names of user
  392. attributes to compare to. If this argument is not provided, the default
  393. is used: ``'username', 'first_name', 'last_name', 'email'``.
  394. Attributes that don't exist are ignored.
  395. The minimum similarity of a rejected password can be set on a scale of 0 to
  396. 1 with the ``max_similarity`` parameter. A setting of 0 rejects all
  397. passwords, whereas a setting of 1 rejects only passwords that are identical
  398. to an attribute's value.
  399. .. class:: CommonPasswordValidator(password_list_path=DEFAULT_PASSWORD_LIST_PATH)
  400. Validates whether the password is not a common password. This converts the
  401. password to lowercase (to do a case-insensitive comparison) and checks it
  402. against a list of 1000 common password created by `Mark Burnett
  403. <https://web.archive.org/web/20150315154609/https://xato.net/passwords/more-top-worst-passwords/>`_.
  404. The ``password_list_path`` can be set to the path of a custom file of
  405. common passwords. This file should contain one lowercase password per line
  406. and may be plain text or gzipped.
  407. .. class:: NumericPasswordValidator()
  408. Validates whether the password is not entirely numeric.
  409. Integrating validation
  410. -----------------------
  411. There are a few functions in ``django.contrib.auth.password_validation`` that
  412. you can call from your own forms or other code to integrate password
  413. validation. This can be useful if you use custom forms for password setting,
  414. or if you have API calls that allow passwords to be set, for example.
  415. .. function:: validate_password(password, user=None, password_validators=None)
  416. Validates a password. If all validators find the password valid, returns
  417. ``None``. If one or more validators reject the password, raises a
  418. :exc:`~django.core.exceptions.ValidationError` with all the error messages
  419. from the validators.
  420. The ``user`` object is optional: if it's not provided, some validators may
  421. not be able to perform any validation and will accept any password.
  422. .. function:: password_changed(password, user=None, password_validators=None)
  423. Informs all validators that the password has been changed. This can be used
  424. by validators such as one that prevents password reuse. This should be
  425. called once the password has been successfully changed.
  426. For subclasses of :class:`~django.contrib.auth.models.AbstractBaseUser`,
  427. the password field will be marked as "dirty" when calling
  428. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_password` which
  429. triggers a call to ``password_changed()`` after the user is saved.
  430. .. function:: password_validators_help_texts(password_validators=None)
  431. Returns a list of the help texts of all validators. These explain the
  432. password requirements to the user.
  433. .. function:: password_validators_help_text_html(password_validators=None)
  434. Returns an HTML string with all help texts in an ``<ul>``. This is
  435. helpful when adding password validation to forms, as you can pass the
  436. output directly to the ``help_text`` parameter of a form field.
  437. .. function:: get_password_validators(validator_config)
  438. Returns a set of validator objects based on the ``validator_config``
  439. parameter. By default, all functions use the validators defined in
  440. :setting:`AUTH_PASSWORD_VALIDATORS`, but by calling this function with an
  441. alternate set of validators and then passing the result into the
  442. ``password_validators`` parameter of the other functions, your custom set
  443. of validators will be used instead. This is useful when you have a typical
  444. set of validators to use for most scenarios, but also have a special
  445. situation that requires a custom set. If you always use the same set
  446. of validators, there is no need to use this function, as the configuration
  447. from :setting:`AUTH_PASSWORD_VALIDATORS` is used by default.
  448. The structure of ``validator_config`` is identical to the
  449. structure of :setting:`AUTH_PASSWORD_VALIDATORS`. The return value of
  450. this function can be passed into the ``password_validators`` parameter
  451. of the functions listed above.
  452. Note that where the password is passed to one of these functions, this should
  453. always be the clear text password - not a hashed password.
  454. Writing your own validator
  455. --------------------------
  456. If Django's built-in validators are not sufficient, you can write your own
  457. password validators. Validators are fairly simple classes. They must implement
  458. two methods:
  459. * ``validate(self, password, user=None)``: validate a password. Return
  460. ``None`` if the password is valid, or raise a
  461. :exc:`~django.core.exceptions.ValidationError` with an error message if the
  462. password is not valid. You must be able to deal with ``user`` being
  463. ``None`` - if that means your validator can't run, simply return ``None``
  464. for no error.
  465. * ``get_help_text()``: provide a help text to explain the requirements to
  466. the user.
  467. Any items in the ``OPTIONS`` in :setting:`AUTH_PASSWORD_VALIDATORS` for your
  468. validator will be passed to the constructor. All constructor arguments should
  469. have a default value.
  470. Here's a basic example of a validator, with one optional setting::
  471. from django.core.exceptions import ValidationError
  472. from django.utils.translation import gettext as _
  473. class MinimumLengthValidator:
  474. def __init__(self, min_length=8):
  475. self.min_length = min_length
  476. def validate(self, password, user=None):
  477. if len(password) < self.min_length:
  478. raise ValidationError(
  479. _("This password must contain at least %(min_length)d characters."),
  480. code='password_too_short',
  481. params={'min_length': self.min_length},
  482. )
  483. def get_help_text(self):
  484. return _(
  485. "Your password must contain at least %(min_length)d characters."
  486. % {'min_length': self.min_length}
  487. )
  488. You can also implement ``password_changed(password, user=None``), which will
  489. be called after a successful password change. That can be used to prevent
  490. password reuse, for example. However, if you decide to store a user's previous
  491. passwords, you should never do so in clear text.