Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a minimum password length when using the built-in Django auth module?

I’m implementing authentication in a Django site using the built-in auth module, including the built-in UserCreationForm.

I’d like to set a minimum length for passwords. However, I can’t find any documentation on how to do this.

Can I configure the auth module’s User module to require this at the database level? Or should I sub-class the UserCreationForm (I’m actually doing this already for unrelated reasons) and add an extra validator that enforces the password length?

like image 711
Paul D. Waite Avatar asked Feb 28 '12 19:02

Paul D. Waite


People also ask

How do I create a custom password validator in Django?

How To Create Your Own Django Password Validator. If you have more specific needs, you can create your own validators. To do so, simply create your own classes based on object and raise a ValidationError if the entered password fails. class NumberValidator(object): def validate(self, password, user=None): if not re.

What is Django default password validator?

By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST.

What is UserAdmin in Django?

Django uses UserAdmin to render the nice admin look for User model. By just using this in our admin.py -file, we can get the same look for our model. from django.contrib.auth.admin import UserAdmin admin.site.register(MyUser, UserAdmin)


2 Answers

I think the easiest way to achieve this is using Django password validation

For minimum length would be enough adding this to settings file:

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 8,
        }
    },
]

There are others validators like NumericPasswordValidator and CommonPasswordValidator

like image 160
Andres Avatar answered Sep 24 '22 19:09

Andres


Especially if you're already using a sub-classed UserCreationForm, I'd say you should definitely just add the validation to it. You should be able to override the clean_password method on the form:

def clean_password(self):
    password = self.cleaned_data.get('password1')
    if len(password) < 8:
        raise ValidationError('Password too short')
    return super(MyUserCreationForm, self).clean_password1()
like image 36
Chris Pratt Avatar answered Sep 22 '22 19:09

Chris Pratt