Gerenciamento de senhas no Django¶
O gerenciamento de senha é algo que não deve ser reinventado desnecessariamente, e o Django se esforça para fornecer um conjunto de ferramentas seguras e flexíveis para gerenciar senhas de usuários. Este documento descreve como o Django armazena senhas, como o armazenamento de “hashes” pode ser configurado, e algumas utilidade para trabalhar com senhas criptografadas.
Ver também
Mesmo que os usuários usem senha fortes, ataques podem ser capazes de bisbilhotar suas conexões. Use conexões HTTPS para evitar o envio de senhas (ou qualquer outro dado sensível) sobre conexões HTTP porque eles estarão vulneráveis a sequestros de senhas.
Como o Django armazena as senhas¶
O Django fornece um sistema flexível de armazenamento de senhas e usa PBKDF2 por padrão.
The password
attribute of a
User
object is a string in this format:
<algorithm>$<iterations>$<salt>$<hash>
Estes são os componentes usados para armazenamento de senha do “User”, separados pelo caracter de sinal do dólar e consistem em: o algoritmo de “hash”, o número de iterações do algoritmo (fator de trabalho), o “salt” randômico, e o “hash” de senha resultante. O algoritmo é um dos vários algoritmos “hash” de via única ou de armazenamento de senha que o Django pode usar; veja abaixo. O iterações descreve o número de vezes que o algoritmo é executado sobre o “hash”. “Salt” é a string randômica inicial usada e o “hash” é o resultado da função de via única.
Por padrão, Django usa o algoritmo PBKDF2 com um hash SHA256, um mecanismo de elasticidade de senha recomendado pelo NIST. Isso deve ser suficiente para a maior parte dos usuários: é bastante seguro, e requer quantidades massivas de tempo computacional para quebrar.
Contudo, dependendo das suas necessidades, você pode escolher um algoritmo diferente, ou até mesmo usar um algoritmo customizado para suprir suas necessidades específicas de segurança. Novamente, a maioria dos usuários não precisam disso – se você não tem certeza, provavelmente não precisa. Se você precisa, por favor, leia:
Django chooses the algorithm to use by consulting the
PASSWORD_HASHERS
setting. This is a list of hashing algorithm
classes that this Django installation supports.
For storing passwords, Django will use the first hasher in
PASSWORD_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 matches
the algorithm name in the stored password. If a stored password names an
algorithm not found in PASSWORD_HASHERS
, trying to verify it will
raise ValueError
.
O padrão para PASSWORD_HASHERS
é:
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",
]
Isso significa que o Django vai usar o PBKFD2 para armazenar todas as senhas, mas vai suportar a conferência de senhas armazenadas com PBKDF2SHA1, argon2, and bcrypt.
As próximas seções descreverão jeitos comuns que usuários avançados podem querer usar para modificar essas configurações.
Usando Argon2 com Django¶
Argon2 is the winner of the 2015 Password Hashing Competition, a community organized open competition to select a next generation hashing algorithm. It’s designed not to be easier to compute on custom hardware than it is to compute on an ordinary CPU. The default variant for the Argon2 password hasher is Argon2id.
Argon2 não é o padrão do Django porque precisa de uma biblioteca de terceiros. A equipe da Competição de Senhas Hashing, contudo, recomenda o uso imediato de Argon2 em vez de outros algoritmos suportados pelo 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 requirement from Django’spyproject.toml
).Modificar
PASSWORD_HASHERS`para listar primeiro ``Argon2PasswordHasher
. Ou seja, no seu arquivo de configurações, você colocaria: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", ]
Mantenha ou adicione quaisquer entradas nessa lista se você precisa que o Django atualize senhas.
Usando bcrypt
com Django¶
Bcrypt é um algoritmo popular de armazenamento de senhas que é especificamente desenhado para armazenamento de senhas de longo prazo. Não é o padrão utilizado pelo Django porque requer uso de bibliotecas de terceiros, mas, já que muita gente pode querer usá-lo, Django suporta o o Bcrypt com mínimo esforço.
Para utilizar Bcrypt como seu algoritmo de armazenamento padrão, faça o seguinte:
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 from Django’spyproject.toml
).Modifique
PASSWORD_HASHERS
para listar primeiroBCryptSHA256PasswordHasher
. Ou seja, no seu arquivo de configurações, você colocará: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", ]
Mantenha ou adicione quaisquer entradas nessa lista se você precisa que o Django atualize senhas.
É isso - agora a sua instalação do Django usará Bcrypt como o algoritmo de armazenamento padrão.
Using scrypt
with Django¶
scrypt is similar to PBKDF2 and bcrypt in utilizing a set number of iterations to slow down brute-force attacks. However, because PBKDF2 and bcrypt do not require a lot of memory, attackers with sufficient resources can launch large-scale parallel attacks in order to speed up the attacking process. scrypt is specifically designed to use more memory compared to other password-based key derivation functions in order to limit the amount of parallelism 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", ]
Mantenha ou adicione quaisquer entradas nessa lista se você precisa que o Django atualize senhas.
Nota
scrypt
requires OpenSSL 1.1+.
Increasing the salt entropy¶
Most password hashes include a salt along with their password hash in order to
protect against rainbow table attacks. The salt itself is a random value which
increases the size and thus the cost of the rainbow table and is currently set
at 128 bits with the salt_entropy
value in the BasePasswordHasher
. As
computing and storage costs decrease this value should be raised. When
implementing your own password hasher you are free to override this value in
order 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 would
provide a salt which would actually contain 131 bits of entropy.
Aumentando o fator de trabalho¶
PBKDF2 e bcrypt¶
The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
hashing. This deliberately slows down attackers, making attacks against hashed
passwords harder. However, as computing power increases, the number of
iterations needs to be increased. We’ve chosen a reasonable default (and will
increase it with each release of Django), but you may wish to tune it up or
down, 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). For
example, to increase the number of iterations used by the default PBKDF2
algorithm:
Create a subclass of
django.contrib.auth.hashers.PBKDF2PasswordHasher
from django.contrib.auth.hashers import PBKDF2PasswordHasher class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher): """ A subclass of PBKDF2PasswordHasher that uses 100 times more iterations. """ iterations = PBKDF2PasswordHasher.iterations * 100
Salve isso em algum lugar no seu projeto. Por exemplo, você pode coloca-lo em um arquivo como
meuprojeto/hashers.py
.Adicione seu novo hasher como a primeira entrada em: setting: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", ]
É isso – agora seu Django install usará mais iterações ao armazenar senhas usando PBKDF2.
Nota
bcrypt rounds
is a logarithmic work factor, e.g. 12 rounds means
2 ** 12
iterations.
Argon2¶
Argon2 has the following attributes that can be customized:
time_cost
controla o número de iterações dentro do hash.memory_cost
controla o tamanho da memória que deve ser usada durante a computação do hash.parallelism
controla quantas CPUs podem ser paralelizadas na computação do hash.
Os valores padrão desses atributos provavelmente estarão bons para você. Se você determinar que o seu hash de senha está muito rápido ou muito lento, você pode ajusta-lo como segue:
Escolha
parallelism
para ser o número de threads que você pode disponibilizar para computar o hash.Escolha
memory_cost
para ser o quanto de memória em KiB que você pode disponibilizar.Ajuste
time_cost
e meça o tempo gasto para gerar o hash de uma senha. Escolha umtime_cost
que tome um tempo aceitável para você. Setime_cost
configurado para 1 for inaceitavelmente lento para você, reduzatime_cost
.
memory_cost
interpretação
O utilitário de linha de comando argon2 e algumas outras bibliotecas interpretam o parâmetro memory_cost
diferentemente do valor que Django usa. A conversão é dada por 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 the computation of the hash. Defaults to0
, which means the default limitation 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
or
block_size
values.
Atualização de senha¶
Quando usuários entram, se suas senhas estão armazenadas com qualquer outra coisa que não o o algoritmo preferido, Django atualizará automaticamente o algoritmo para o preferido. Isto significa que instalações antigas de Django ficarão mais seguras a medida que os usuários entram, isso também significa que você pode mudar para novos (e melhores) algoritmos de armazenamento quando eles forem inventados.
However, Django can only upgrade passwords that use algorithms mentioned in
PASSWORD_HASHERS
, so as you upgrade to new systems you should make
sure never to remove entries from this list. If you do, users using
unmentioned algorithms won’t be able to upgrade. Hashed passwords will be
updated when increasing (or decreasing) the number of PBKDF2 iterations, bcrypt
rounds, or argon2 attributes.
Esteja ciente que se nem todas as senhas armazenadas em seu banco de dados estiverem codificadas através do algoritmo padrão de hash, você pode estar vulnerável a ataques de enumeração de usuários baseado em tempo devido a uma diferença entre a duração do pedido de login para um usuário com uma senha codificada por um algoritmo não-padrão e a duração de um pedido de login para um usuário inexistente (o qual roda o hash padrão). Você pode ser capaz de mitigar isso:ref:atualizando hashes de senhas mais antigos <wrapping-password-hashers>.
Atualização de senha sem exigência de login¶
If you have an existing database with an older, weak hash such as MD5, you might want to upgrade those hashes yourself instead of waiting for the upgrade to happen when a user logs in (which may never happen if a user doesn’t return to your site). In this case, you can use a “wrapped” password hasher.
For this example, we’ll migrate a collection of MD5 hashes to use
PBKDF2(MD5(password)) and add the corresponding password hasher for checking
if a user entered the correct password on login. We assume we’re using the
built-in User
model and that our project has an accounts
app. You can
modify the pattern to work with any algorithm or with a custom user model.
Primeiro, vamos adicionar um hasher customizado:
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)
A migração pode parecer algo como:
from django.db import migrations
from ..hashers import PBKDF2WrappedMD5PasswordHasher
def 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),
]
Tenha cuidado que essa migração deve ser tomará uma ordem de vários minutos para milhares de usuários, dependendo da velocidade do seu hardware.
Finalmente, vamos adicionar a configuração PASSWORD_HASHERS
:
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
"accounts.hashers.PBKDF2WrappedMD5PasswordHasher",
]
Inclua quaisquer outros hashers que seu site usa nessa lista.
Hashers incluídos¶
A lista completa de hashers incluídas no Django são:
[
"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",
]
Os nomes de algoritmos correspondentes são:
pbkdf2_sha256
pbkdf2_sha1
argon2
bcrypt_sha256
bcrypt
scrypt
md5
Escrevendo seu próprio hasher¶
If you write your own password hasher that contains a work factor such as a
number of iterations, you should implement a
harden_runtime(self, password, encoded)
method to bridge the runtime gap
between the work factor supplied in the encoded
password and the default
work factor of the hasher. This prevents a user enumeration timing attack due
to difference between a login request for a user with a password encoded in an
older number of iterations and a nonexistent user (which runs the default
hasher’s default number of iterations).
Taking PBKDF2 as example, if encoded
contains 20,000 iterations and the
hasher’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 functions
to create and validate hashed passwords. You can use them independently
from the User
model.
- check_password(password, encoded, setter=None, preferred='default')[código-fonte]¶
- acheck_password(password, encoded, asetter=None, preferred='default')¶
Asynchronous version:
acheck_password()
If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function
check_password()
. It takes two mandatory arguments: the plain-text password to check, and the full value of a user’spassword
field in the database to check against. It returnsTrue
if they match,False
otherwise. Optionally, you can pass a callablesetter
that takes the password and will be called when you need to regenerate it. You can also passpreferred
to change a hashing algorithm if you don’t want to use the default (first entry ofPASSWORD_HASHERS
setting). See Hashers incluídos for the algorithm name of each hasher.
- make_password(password, salt=None, hasher='default')[código-fonte]¶
Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text (string or bytes). Optionally, you can provide a salt and a hashing algorithm to use, if you don’t want to use the defaults (first entry of
PASSWORD_HASHERS
setting). See Hashers incluídos for the algorithm name of each hasher. If the password argument isNone
, an unusable password is returned (one that will never be accepted bycheck_password()
).
- is_password_usable(encoded_password)[código-fonte]¶
Returns
False
if the password is a result ofUser.set_unusable_password()
.
Validação de senha¶
Users often choose poor passwords. To help mitigate this problem, Django offers pluggable password validation. You can configure multiple password validators at the same time. A few validators are included in Django, but you can write your own as well.
Each password validator must provide a help text to explain the requirements to the user, validate a given password and return an error message if it does not meet the requirements, and optionally define a callback to be notified when the password for a user has been changed. Validators can also have optional settings 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 are
applied. 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 and
in the createsuperuser
and changepassword
management
commands. Validators aren’t applied at the model level, for example in
User.objects.create_user()
and create_superuser()
, because we assume
that developers, not users, interact with Django at that level and also because
model validation doesn’t automatically run as part of creating models.
Nota
Validação de senha pode previnir que o usuário utilize muitos tipos de senhas fracas. No entanto, o fato de uma senha passar em todos os validadores não garante que a senha é forte. Existem muitos outros fatores que podem enfraquecer uma senha que não é detectado nem mesmo pelos validadores de senha mais avançados.
Habilitando validação de senha¶
A validação de senha é configurada utilizando a variável AUTH_PASSWORD_VALIDATORS
:
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",
},
]
Este exemplo habilita todos os quatro validadores incluídos:
UserAttributeSimilarityValidator
, que verifica a similaridade entre a senha e um conjunto de atributos do usuário.MinimumLengthValidator
, which checks whether the password meets a minimum length. This validator is configured with a custom option: it now requires the minimum length to be nine characters, instead of the default eight.CommonPasswordValidator
, which checks whether the password occurs in a list of common passwords. By default, it compares to an included list of 20,000 common passwords.NumericPasswordValidator
, que verifica se a senha não é completamente numérica.
For UserAttributeSimilarityValidator
and CommonPasswordValidator
,
we’re using the default settings in this example. NumericPasswordValidator
has no settings.
Os textos de ajuda e qualquer erro dos validadores de senha sempre retornam na ordem que eles foram listados no AUTH_PASSWORD_VALIDATORS
.
Validadores incluídos¶
Django inclui quatro validadores:
- class MinimumLengthValidator(min_length=8)[código-fonte]¶
Validates that the password is of a minimum length. The minimum length can be customized with the
min_length
parameter.- get_error_message()[código-fonte]¶
- New in Django 5.2.
A hook for customizing the
ValidationError
error message. Defaults to"This password is too short. It must contain at least <min_length> characters."
.
- get_help_text()[código-fonte]¶
A hook for customizing the validator’s help text. Defaults to
"Your password must contain at least <min_length> characters."
.
- class UserAttributeSimilarityValidator(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)[código-fonte]¶
Validates that the password is sufficiently different from certain attributes of the user.
O parâmetro
user_attributes
deve ser um iterável de nomes de atributos de usuário para serem comparados. Se este argumento não for fornecido, o padrão será utilizado:'username', 'first_name', 'last_name', 'email'
. Atributos que não existem são ignorados.The maximum allowed similarity of passwords can be set on a scale of 0.1 to 1.0 with the
max_similarity
parameter. This is compared to the result ofdifflib.SequenceMatcher.quick_ratio()
. A value of 0.1 rejects passwords unless they are substantially different from theuser_attributes
, whereas a value of 1.0 rejects only passwords that are identical to an attribute’s value.- get_error_message()[código-fonte]¶
- New in Django 5.2.
A hook for customizing the
ValidationError
error message. Defaults to"The password is too similar to the <user_attribute>."
.
- get_help_text()[código-fonte]¶
A hook for customizing the validator’s help text. Defaults to
"Your password can’t be too similar to your other personal information."
.
- class CommonPasswordValidator(password_list_path=DEFAULT_PASSWORD_LIST_PATH)[código-fonte]¶
Validates that the password is not a common password. This converts the password to lowercase (to do a case-insensitive comparison) and checks it against 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 of common passwords. This file should contain one lowercase password per line and may be plain text or gzipped.- get_error_message()[código-fonte]¶
- New in Django 5.2.
A hook for customizing the
ValidationError
error message. Defaults to"This password is too common."
.
- get_help_text()[código-fonte]¶
A hook for customizing the validator’s help text. Defaults to
"Your password can’t be a commonly used password."
.
- class NumericPasswordValidator[código-fonte]¶
Validate that the password is not entirely numeric.
- get_error_message()[código-fonte]¶
- New in Django 5.2.
A hook for customizing the
ValidationError
error message. Defaults to"This password is entirely numeric."
.
- get_help_text()[código-fonte]¶
A hook for customizing the validator’s help text. Defaults to
"Your password can’t be entirely numeric."
.
Integrating validation¶
There are a few functions in django.contrib.auth.password_validation
that
you can call from your own forms or other code to integrate password
validation. 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)[código-fonte]¶
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 messages from the validators.The
user
object is optional: if it’s not provided, some validators may not be able to perform any validation and will accept any password.
- password_changed(password, user=None, password_validators=None)[código-fonte]¶
Informs all validators that the password has been changed. This can be used by validators such as one that prevents password reuse. This should be called once the password has been successfully changed.
For subclasses of
AbstractBaseUser
, the password field will be marked as “dirty” when callingset_password()
which triggers a call topassword_changed()
after the user is saved.
- password_validators_help_texts(password_validators=None)[código-fonte]¶
Returns a list of the help texts of all validators. These explain the password requirements to the user.
- password_validators_help_text_html(password_validators=None)¶
Returns an HTML string with all help texts in an
<ul>
. This is helpful when adding password validation to forms, as you can pass the output directly to thehelp_text
parameter of a form field.
- get_password_validators(validator_config)[código-fonte]¶
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 an alternate set of validators and then passing the result into thepassword_validators
parameter of the other functions, your custom set of validators will be used instead. This is useful when you have a typical set of validators to use for most scenarios, but also have a special situation that requires a custom set. If you always use the same set of validators, there is no need to use this function, as the configuration fromAUTH_PASSWORD_VALIDATORS
is used by default.The structure of
validator_config
is identical to the structure ofAUTH_PASSWORD_VALIDATORS
. The return value of this function can be passed into thepassword_validators
parameter of the functions listed above.
Note that where the password is passed to one of these functions, this should always be the clear text password - not a hashed password.
Escrevendo seu próprio validador¶
If Django’s built-in validators are not sufficient, you can write your own password validators. Validators have a fairly small interface. They must implement two methods:
validate(self, password, user=None)
: validate a password. ReturnNone
if the password is valid, or raise aValidationError
with an error message if the password is not valid. You must be able to deal withuser
beingNone
- if that means your validator can’t run, returnNone
for no error.get_help_text()
: provide a help text to explain the requirements to the user.
Any items in the OPTIONS
in AUTH_PASSWORD_VALIDATORS
for your
validator will be passed to the constructor. All constructor arguments should
have a default value.
Here’s a basic example of a validator, with one optional setting:
from django.core.exceptions import ValidationError
from 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 will
be called after a successful password change. That can be used to prevent
password reuse, for example. However, if you decide to store a user’s previous
passwords, you should never do so in clear text.