2
0

passwords.txt 32 KB

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