Password management is something that should generally not be reinventedunnecessarily, and Django endeavors to provide a secure and flexible set oftools for managing user passwords. This document describes how Django storespasswords, how the storage hashing can be configured, and some utilities towork with hashed passwords.
How Django stores passwords¶
Django provides a flexible password storage system and uses PBKDF2 by default.
The password
attribute of aUser
object is a string in this format:
<algorithm>$<iterations>$<salt>$<hash>
Those are the components used for storing a User’s password, separated by thedollar-sign character and consist of: the hashing algorithm, the number ofalgorithm iterations (work factor), the random salt, and the resulting passwordhash. The algorithm is one of a number of one-way hashing or password storagealgorithms Django can use; see below. Iterations describe the number of timesthe algorithm is run over the hash. Salt is the random seed used and the hashis the result of the one-way function.
By default, Django uses the PBKDF2 algorithm with a SHA256 hash, apassword stretching mechanism recommended by NIST. This should besufficient for most users: it’s quite secure, requiring massiveamounts of computing time to break.
However, depending on your requirements, you may choose a differentalgorithm, or even use a custom algorithm to match your specificsecurity situation. Again, most users shouldn’t need to do this – ifyou’re not sure, you probably don’t. If you do, please read on:
Django chooses the algorithm to use by consulting thePASSWORD_HASHERS
setting. This is a list of hashing algorithmclasses that this Django installation supports.
For storing passwords, Django will use the first hasher inPASSWORD_HASHERS
. To store new passwords with a different algorithm,put your preferred algorithm first in PASSWORD_HASHERS
.
For verifying passwords, Django will find the hasher in the list that matchesthe algorithm name in the stored password. If a stored password names analgorithm not found in PASSWORD_HASHERS
, trying to verify it willraise ValueError
.
The default for PASSWORD_HASHERS
is:
PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher",]
This means that Django will use PBKDF2 to store all passwords but will supportchecking passwords stored with PBKDF2SHA1, argon2, and bcrypt.
The next few sections describe a couple of common ways advanced users may wantto modify this setting.
Using Argon2 with Django¶
Argon2 is the winner of the 2015 Password Hashing Competition, a communityorganized open competition to select a next generation hashing algorithm. It’sdesigned not to be easier to compute on custom hardware than it is to computeon an ordinary CPU. The default variant for the Argon2 password hasher isArgon2id.
Argon2 is not the default for Django because it requires a third-partylibrary. The Password Hashing Competition panel, however, recommends immediateuse of Argon2 rather than the other algorithms supported by Django.
To use Argon2id as your default storage algorithm, do the following:
Install the argon2-cffi package. This can be done by running
python -m pip install django[argon2]
, which is equivalent topython -m pip install argon2-cffi
(along with any version requirementfrom Django’ssetup.cfg
).Modify
PASSWORD_HASHERS
to listArgon2PasswordHasher
first.That is, in your settings file, you’d put:PASSWORD_HASHERS = [ "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher",]
Keep and/or add any entries in this list if you need Django to upgradepasswords.
Using bcrypt
with Django¶
Bcrypt is a popular password storage algorithm that’s specifically designedfor long-term password storage. It’s not the default used by Django since itrequires the use of third-party libraries, but since many people may want touse it Django supports bcrypt with minimal effort.
To use Bcrypt as your default storage algorithm, do the following:
Install the bcrypt package. This can be done by running
python -m pip install django[bcrypt]
, which is equivalent topython -m pip install bcrypt
(along with any version requirement fromDjango’ssetup.cfg
).Modify
PASSWORD_HASHERS
to listBCryptSHA256PasswordHasher
first. That is, in your settings file, you’d put:PASSWORD_HASHERS = [ "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher",]
Keep and/or add any entries in this list if you need Django to upgradepasswords.
That’s it – now your Django install will use Bcrypt as the default storagealgorithm.
Using scrypt
with Django¶
scrypt is similar to PBKDF2 and bcrypt in utilizing a set number of iterationsto slow down brute-force attacks. However, because PBKDF2 and bcrypt do notrequire a lot of memory, attackers with sufficient resources can launchlarge-scale parallel attacks in order to speed up the attacking process.scrypt is specifically designed to use more memory compared to otherpassword-based key derivation functions in order to limit the amount ofparallelism an attacker can use, see RFC 7914 for more details.
To use scrypt as your default storage algorithm, do the following:
Modify
PASSWORD_HASHERS
to listScryptPasswordHasher
first.That is, in your settings file:PASSWORD_HASHERS = [ "django.contrib.auth.hashers.ScryptPasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",]
Keep and/or add any entries in this list if you need Django to upgradepasswords.
Note
scrypt
requires OpenSSL 1.1+.
Increasing the salt entropy¶
Most password hashes include a salt along with their password hash in order toprotect against rainbow table attacks. The salt itself is a random value whichincreases the size and thus the cost of the rainbow table and is currently setat 128 bits with the salt_entropy
value in the BasePasswordHasher
. Ascomputing and storage costs decrease this value should be raised. Whenimplementing your own password hasher you are free to override this value inorder to use a desired entropy level for your password hashes. salt_entropy
is measured in bits.
Implementation detail
Due to the method in which salt values are stored the salt_entropy
value is effectively a minimum value. For instance a value of 128 wouldprovide a salt which would actually contain 131 bits of entropy.
Increasing the work factor¶
PBKDF2 and bcrypt¶
The PBKDF2 and bcrypt algorithms use a number of iterations or rounds ofhashing. This deliberately slows down attackers, making attacks against hashedpasswords harder. However, as computing power increases, the number ofiterations needs to be increased. We’ve chosen a reasonable default (and willincrease it with each release of Django), but you may wish to tune it up ordown, depending on your security needs and available processing power. To do so,you’ll subclass the appropriate algorithm and override the iterations
parameter (use the rounds
parameter when subclassing a bcrypt hasher). Forexample, to increase the number of iterations used by the default PBKDF2algorithm:
Create a subclass of
django.contrib.auth.hashers.PBKDF2PasswordHasher
from django.contrib.auth.hashers import PBKDF2PasswordHasherclass MyPBKDF2PasswordHasher(PBKDF2PasswordHasher): """ A subclass of PBKDF2PasswordHasher that uses 100 times more iterations. """ iterations = PBKDF2PasswordHasher.iterations * 100
Save this somewhere in your project. For example, you might put this ina file like
myproject/hashers.py
.Add your new hasher as the first entry in
PASSWORD_HASHERS
:PASSWORD_HASHERS = [ "myproject.hashers.MyPBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher",]
That’s it – now your Django install will use more iterations when itstores passwords using PBKDF2.
Note
bcrypt rounds
is a logarithmic work factor, e.g. 12 rounds means2 ** 12
iterations.
Argon2¶
Argon2 has the following attributes that can be customized:
time_cost
controls the number of iterations within the hash.memory_cost
controls the size of memory that must be used during thecomputation of the hash.parallelism
controls how many CPUs the computation of the hash can beparallelized on.
The default values of these attributes are probably fine for you. If youdetermine that the password hash is too fast or too slow, you can tweak it asfollows:
- Choose
parallelism
to be the number of threads you canspare computing the hash. - Choose
memory_cost
to be the KiB of memory you can spare. - Adjust
time_cost
and measure the time hashing a password takes.Pick atime_cost
that takes an acceptable time for you.Iftime_cost
set to 1 is unacceptably slow, lowermemory_cost
.
memory_cost
interpretation
The argon2 command-line utility and some other libraries interpret thememory_cost
parameter differently from the value that Django uses. Theconversion is given by memory_cost == 2 ** memory_cost_commandline
.
scrypt
¶
scrypt has the following attributes that can be customized:
work_factor
controls the number of iterations within the hash.block_size
parallelism
controls how many threads will run in parallel.maxmem
limits the maximum size of memory that can be used during thecomputation of the hash. Defaults to0
, which means the defaultlimitation from the OpenSSL library.
We’ve chosen reasonable defaults, but you may wish to tune it up or down,depending on your security needs and available processing power.
Estimating memory usage
The minimum memory requirement of scrypt is:
work_factor * 2 * block_size * 64
so you may need to tweak maxmem
when changing the work_factor
orblock_size
values.
Password upgrading¶
When users log in, if their passwords are stored with anything other thanthe preferred algorithm, Django will automatically upgrade the algorithmto the preferred one. This means that old installs of Django will getautomatically more secure as users log in, and it also means that youcan switch to new (and better) storage algorithms as they get invented.
However, Django can only upgrade passwords that use algorithms mentioned inPASSWORD_HASHERS
, so as you upgrade to new systems you should makesure never to remove entries from this list. If you do, users usingunmentioned algorithms won’t be able to upgrade. Hashed passwords will beupdated when increasing (or decreasing) the number of PBKDF2 iterations, bcryptrounds, or argon2 attributes.
Be aware that if all the passwords in your database aren’t encoded in thedefault hasher’s algorithm, you may be vulnerable to a user enumeration timingattack due to a difference between the duration of a login request for a userwith a password encoded in a non-default algorithm and the duration of a loginrequest for a nonexistent user (which runs the default hasher). You may be ableto mitigate this by upgrading older password hashes.
Password upgrading without requiring a login¶
If you have an existing database with an older, weak hash such as MD5, youmight want to upgrade those hashes yourself instead of waiting for the upgradeto happen when a user logs in (which may never happen if a user doesn’t returnto your site). In this case, you can use a “wrapped” password hasher.
For this example, we’ll migrate a collection of MD5 hashes to usePBKDF2(MD5(password)) and add the corresponding password hasher for checkingif a user entered the correct password on login. We assume we’re using thebuilt-in User
model and that our project has an accounts
app. You canmodify the pattern to work with any algorithm or with a custom user model.
First, we’ll add the custom hasher:
accounts/hashers.py
¶
from django.contrib.auth.hashers import ( PBKDF2PasswordHasher, MD5PasswordHasher,)class PBKDF2WrappedMD5PasswordHasher(PBKDF2PasswordHasher): algorithm = "pbkdf2_wrapped_md5" def encode_md5_hash(self, md5_hash, salt, iterations=None): return super().encode(md5_hash, salt, iterations) def encode(self, password, salt, iterations=None): _, _, md5_hash = MD5PasswordHasher().encode(password, salt).split("$", 2) return self.encode_md5_hash(md5_hash, salt, iterations)
The data migration might look something like:
accounts/migrations/0002_migrate_md5_passwords.py
¶
from django.db import migrationsfrom ..hashers import PBKDF2WrappedMD5PasswordHasherdef forwards_func(apps, schema_editor): User = apps.get_model("auth", "User") users = User.objects.filter(password__startswith="md5$") hasher = PBKDF2WrappedMD5PasswordHasher() for user in users: algorithm, salt, md5_hash = user.password.split("$", 2) user.password = hasher.encode_md5_hash(md5_hash, salt) user.save(update_fields=["password"])class Migration(migrations.Migration): dependencies = [ ("accounts", "0001_initial"), # replace this with the latest migration in contrib.auth ("auth", "####_migration_name"), ] operations = [ migrations.RunPython(forwards_func), ]
Be aware that this migration will take on the order of several minutes forseveral thousand users, depending on the speed of your hardware.
Finally, we’ll add a PASSWORD_HASHERS
setting:
mysite/settings.py
¶
PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "accounts.hashers.PBKDF2WrappedMD5PasswordHasher",]
Include any other hashers that your site uses in this list.
Included hashers¶
The full list of hashers included in Django is:
[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.BCryptPasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher",]
The corresponding algorithm names are:
pbkdf2_sha256
pbkdf2_sha1
argon2
bcrypt_sha256
bcrypt
scrypt
md5
Writing your own hasher¶
If you write your own password hasher that contains a work factor such as anumber of iterations, you should implement aharden_runtime(self, password, encoded)
method to bridge the runtime gapbetween the work factor supplied in the encoded
password and the defaultwork factor of the hasher. This prevents a user enumeration timing attack dueto difference between a login request for a user with a password encoded in anolder number of iterations and a nonexistent user (which runs the defaulthasher’s default number of iterations).
Taking PBKDF2 as example, if encoded
contains 20,000 iterations and thehasher’s default iterations
is 30,000, the method should run password
through another 10,000 iterations of PBKDF2.
If your hasher doesn’t have a work factor, implement the method as a no-op(pass
).
Manually managing a user’s password¶
The django.contrib.auth.hashers module provides a set of functionsto create and validate hashed passwords. You can use them independentlyfrom the User
model.
check_password
(password, encoded, setter=None, preferred='default')¶If you’d like to manually authenticate a user by comparing a plain-textpassword to the hashed password in the database, use the conveniencefunction check_password(). It takes two mandatory arguments: theplain-text password to check, and the full value of a user’s
password
field in the database to check against. It returnsTrue
if they match,False
otherwise. Optionally, you can pass a callablesetter
thattakes the password and will be called when you need to regenerate it. Youcan also passpreferred
to change a hashing algorithm if you don’t wantto use the default (first entry ofPASSWORD_HASHERS
setting). SeeIncluded hashers for the algorithm name of each hasher.
make_password
(password, salt=None, hasher='default')¶Creates a hashed password in the format used by this application. It takesone mandatory argument: the password in plain-text (string or bytes).Optionally, you can provide a salt and a hashing algorithm to use, if youdon’t want to use the defaults (first entry of
PASSWORD_HASHERS
setting). See Included hashers for the algorithm name of eachhasher. If the password argument isNone
, an unusable password isreturned (one that will never be accepted by check_password()).
is_password_usable
(encoded_password)¶Returns
False
if the password is a result ofUser.set_unusable_password()
.
Password validation¶
Users often choose poor passwords. To help mitigate this problem, Djangooffers pluggable password validation. You can configure multiple passwordvalidators at the same time. A few validators are included in Django, but youcan write your own as well.
Each password validator must provide a help text to explain the requirements tothe user, validate a given password and return an error message if it does notmeet the requirements, and optionally define a callback to be notified whenthe password for a user has been changed. Validators can also have optionalsettings to fine tune their behavior.
Validation is controlled by the AUTH_PASSWORD_VALIDATORS
setting.The default for the setting is an empty list, which means no validators areapplied. In new projects created with the default startproject
template, a set of validators is enabled by default.
By default, validators are used in the forms to reset or change passwords andin the createsuperuser
and changepassword
managementcommands. Validators aren’t applied at the model level, for example inUser.objects.create_user()
and create_superuser()
, because we assumethat developers, not users, interact with Django at that level and also becausemodel validation doesn’t automatically run as part of creating models.
Note
Password validation can prevent the use of many types of weak passwords.However, the fact that a password passes all the validators doesn’tguarantee that it is a strong password. There are many factors that canweaken a password that are not detectable by even the most advancedpassword validators.
Enabling password validation¶
Password validation is configured in theAUTH_PASSWORD_VALIDATORS
setting:
AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": { "min_length": 9, }, }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", },]
This example enables all four included validators:
UserAttributeSimilarityValidator
, which checks the similarity betweenthe password and a set of attributes of the user.MinimumLengthValidator
, which checks whether the password meets a minimumlength. This validator is configured with a custom option: it now requiresthe minimum length to be nine characters, instead of the default eight.CommonPasswordValidator
, which checks whether the password occurs in alist of common passwords. By default, it compares to an included list of20,000 common passwords.NumericPasswordValidator
, which checks whether the password isn’tentirely numeric.
For UserAttributeSimilarityValidator
and CommonPasswordValidator
,we’re using the default settings in this example. NumericPasswordValidator
has no settings.
The help texts and any errors from password validators are always returned inthe order they are listed in AUTH_PASSWORD_VALIDATORS
.
Included validators¶
Django includes four validators:
- class
MinimumLengthValidator
(min_length=8)¶ Validates that the password is of a minimum length.The minimum length can be customized with the
min_length
parameter.
- class
UserAttributeSimilarityValidator
(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)¶ Validates that the password is sufficiently different from certainattributes of the user.
The
user_attributes
parameter should be an iterable of names of userattributes to compare to. If this argument is not provided, the defaultis used:'username', 'first_name', 'last_name', 'email'
.Attributes that don’t exist are ignored.The maximum allowed similarity of passwords can be set on a scale of 0.1to 1.0 with the
max_similarity
parameter. This is compared to theresult ofdifflib.SequenceMatcher.quick_ratio()
. A value of 0.1rejects passwords unless they are substantially different from theuser_attributes
, whereas a value of 1.0 rejects only passwords that areidentical to an attribute’s value.Changed in Django 2.2.26:
The
max_similarity
parameter was limited to a minimum value of 0.1.
- class
CommonPasswordValidator
(password_list_path=DEFAULT_PASSWORD_LIST_PATH)¶ Validates that the password is not a common password. This converts thepassword to lowercase (to do a case-insensitive comparison) and checks itagainst a list of 20,000 common password created by Royce Williams.
The
password_list_path
can be set to the path of a custom file ofcommon passwords. This file should contain one lowercase password per lineand may be plain text or gzipped.Changed in Django 4.2:
The list of 20,000 common passwords was updated to the most recentversion.
- class
NumericPasswordValidator
¶ Validate that the password is not entirely numeric.
Integrating validation¶
There are a few functions in django.contrib.auth.password_validation
thatyou can call from your own forms or other code to integrate passwordvalidation. This can be useful if you use custom forms for password setting,or if you have API calls that allow passwords to be set, for example.
validate_password
(password, user=None, password_validators=None)¶Validates a password. If all validators find the password valid, returns
None
. If one or more validators reject the password, raises aValidationError
with all the error messagesfrom the validators.The
user
object is optional: if it’s not provided, some validators maynot be able to perform any validation and will accept any password.
password_changed
(password, user=None, password_validators=None)¶Informs all validators that the password has been changed. This can be usedby validators such as one that prevents password reuse. This should becalled once the password has been successfully changed.
For subclasses of
AbstractBaseUser
,the password field will be marked as “dirty” when callingset_password()
whichtriggers a call topassword_changed()
after the user is saved.
password_validators_help_texts
(password_validators=None)¶Returns a list of the help texts of all validators. These explain thepassword requirements to the user.
password_validators_help_text_html
(password_validators=None)¶Returns an HTML string with all help texts in an
<ul>
. This ishelpful when adding password validation to forms, as you can pass theoutput directly to thehelp_text
parameter of a form field.
get_password_validators
(validator_config)¶Returns a set of validator objects based on the
validator_config
parameter. By default, all functions use the validators defined inAUTH_PASSWORD_VALIDATORS
, but by calling this function with analternate set of validators and then passing the result into thepassword_validators
parameter of the other functions, your custom setof validators will be used instead. This is useful when you have a typicalset of validators to use for most scenarios, but also have a specialsituation that requires a custom set. If you always use the same setof validators, there is no need to use this function, as the configurationfromAUTH_PASSWORD_VALIDATORS
is used by default.The structure of
validator_config
is identical to thestructure ofAUTH_PASSWORD_VALIDATORS
. The return value ofthis function can be passed into thepassword_validators
parameterof the functions listed above.
Note that where the password is passed to one of these functions, this shouldalways be the clear text password - not a hashed password.
Writing your own validator¶
If Django’s built-in validators are not sufficient, you can write your ownpassword validators. Validators have a fairly small interface. They mustimplement two methods:
validate(self, password, user=None)
: validate a password. ReturnNone
if the password is valid, or raise aValidationError
with an error message if thepassword is not valid. You must be able to deal withuser
beingNone
- if that means your validator can’t run, returnNone
for noerror.get_help_text()
: provide a help text to explain the requirements tothe user.
Any items in the OPTIONS
in AUTH_PASSWORD_VALIDATORS
for yourvalidator will be passed to the constructor. All constructor arguments shouldhave a default value.
Here’s a basic example of a validator, with one optional setting:
from django.core.exceptions import ValidationErrorfrom django.utils.translation import gettext as _class MinimumLengthValidator: def __init__(self, min_length=8): self.min_length = min_length def validate(self, password, user=None): if len(password) < self.min_length: raise ValidationError( _("This password must contain at least %(min_length)d characters."), code="password_too_short", params={"min_length": self.min_length}, ) def get_help_text(self): return _( "Your password must contain at least %(min_length)d characters." % {"min_length": self.min_length} )
You can also implement password_changed(password, user=None
), which willbe called after a successful password change. That can be used to preventpassword reuse, for example. However, if you decide to store a user’s previouspasswords, you should never do so in clear text.