passwords.txt 28 KB

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