passwords.txt 27 KB

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