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