使用 django.contrib.auth.views.password_change 强制执行密码强度要求

发布于 2024-10-21 06:47:36 字数 177 浏览 3 评论 0原文

我们有一个 Django 应用程序,需要特定级别的密码复杂性。目前,我们通过客户端 JavaScript 强制执行此操作,但只要有适当的动机,就可以轻松地击败它。

我似乎无法找到有关使用 django contrib 内置视图设置服务器端密码强度验证的任何具体信息。在我开始重新发明轮子之前,是否有适当的方法来处理这个需求?

We have a Django application that requires a specific level of password complexity. We currently enforce this via client-side JavaScript which can easily be defeated by someone who is appropriately motivated.

I cannot seem to find any specific information about setting up server-side password strength validation using the django contrib built in views. Before I go about re-inventing the wheel, is there a proper way to handle this requirement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

微凉 2024-10-28 06:47:36

我还为此准备了一个自定义表格。在 urls.py 中指定您的自定义表单:

(r'^change_password/

继承自 PasswordChangeForm 并实现验证:

from django import forms
from django.contrib import auth

class ValidatingPasswordChangeForm(auth.forms.PasswordChangeForm):
    MIN_LENGTH = 8

    def clean_new_password1(self):
        password1 = self.cleaned_data.get('new_password1')

        # At least MIN_LENGTH long
        if len(password1) < self.MIN_LENGTH:
            raise forms.ValidationError("The new password must be at least %d characters long." % self.MIN_LENGTH)

        # At least one letter and one non-letter
        first_isalpha = password1[0].isalpha()
        if all(c.isalpha() == first_isalpha for c in password1):
            raise forms.ValidationError("The new password must contain at least one letter and at least one digit or" \
                                        " punctuation character.")

        # ... any other validation you want ...

        return password1
, 'django.contrib.auth.views.password_change', {'password_change_form': ValidatingPasswordChangeForm}),

继承自 PasswordChangeForm 并实现验证:

I also went with a custom form for this. In urls.py specify your custom form:

(r'^change_password/

Inherit from PasswordChangeForm and implement validation:

from django import forms
from django.contrib import auth

class ValidatingPasswordChangeForm(auth.forms.PasswordChangeForm):
    MIN_LENGTH = 8

    def clean_new_password1(self):
        password1 = self.cleaned_data.get('new_password1')

        # At least MIN_LENGTH long
        if len(password1) < self.MIN_LENGTH:
            raise forms.ValidationError("The new password must be at least %d characters long." % self.MIN_LENGTH)

        # At least one letter and one non-letter
        first_isalpha = password1[0].isalpha()
        if all(c.isalpha() == first_isalpha for c in password1):
            raise forms.ValidationError("The new password must contain at least one letter and at least one digit or" \
                                        " punctuation character.")

        # ... any other validation you want ...

        return password1
, 'django.contrib.auth.views.password_change', {'password_change_form': ValidatingPasswordChangeForm}),

Inherit from PasswordChangeForm and implement validation:

倾城月光淡如水﹏ 2024-10-28 06:47:36

Django 1.9 提供了内置的密码验证帮助防止用户使用弱密码。它可以通过修改项目中的 AUTH_PASSWORD_VALIDATORS 设置来启用。默认情况下,Django 带有以下验证器:

  • UserAttributeSimilarityValidator,它检查之间的相似性
    密码和用户的一组属性。
  • MinimumLengthValidator,它只是检查密码是否
    满足最小长度。该验证器配置有自定义
    选项:现在要求最小长度为九个字符,
    而不是默认的八个。
  • CommonPasswordValidator,用于检查
    该密码是否出现在常用密码列表中。经过
    默认情况下,它会与包含的 1000 个常用密码列表进行比较。
  • NumericPasswordValidator,检查密码是否不正确
    完全数字。

此示例启用所有四个包含的验证器:

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',
    },
]

Django 1.9 offers a built-in password validation to help prevent the usage of weak passwords by users. It's enabled by modifing the AUTH_PASSWORD_VALIDATORS setting in our project. By default Django comes with following validators:

  • UserAttributeSimilarityValidator, which checks the similarity between
    the password and a set of attributes of the user.
  • MinimumLengthValidator, which simply 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 1000 common passwords.
  • NumericPasswordValidator, which checks whether the password isn’t
    entirely numeric.

This example enables all four included 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',
    },
]
壹場煙雨 2024-10-28 06:47:36

正如一些人使用自定义验证器所回避的那样,这是我将采取的方法...

创建一个验证器:

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _

def validate_password_strength(value):
    """Validates that a password is as least 7 characters long and has at least
    1 digit and 1 letter.
    """
    min_length = 7

    if len(value) < min_length:
        raise ValidationError(_('Password must be at least {0} characters '
                                'long.').format(min_length))

    # check for digit
    if not any(char.isdigit() for char in value):
        raise ValidationError(_('Password must contain at least 1 digit.'))

    # check for letter
    if not any(char.isalpha() for char in value):
        raise ValidationError(_('Password must contain at least 1 letter.'))

然后将验证器添加到您要验证的表单字段中:

from django.contrib.auth.forms import SetPasswordForm

class MySetPasswordForm(SetPasswordForm):

    def __init__(self, *args, **kwargs):
        super(MySetPasswordForm, self).__init__(*args, **kwargs)
        self.fields['new_password1'].validators.append(validate_password_strength)

As some eluded to with the custom validators, here's the approach I would take...

Create a validator:

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _

def validate_password_strength(value):
    """Validates that a password is as least 7 characters long and has at least
    1 digit and 1 letter.
    """
    min_length = 7

    if len(value) < min_length:
        raise ValidationError(_('Password must be at least {0} characters '
                                'long.').format(min_length))

    # check for digit
    if not any(char.isdigit() for char in value):
        raise ValidationError(_('Password must contain at least 1 digit.'))

    # check for letter
    if not any(char.isalpha() for char in value):
        raise ValidationError(_('Password must contain at least 1 letter.'))

Then add the validator to the form field you're looking to validate:

from django.contrib.auth.forms import SetPasswordForm

class MySetPasswordForm(SetPasswordForm):

    def __init__(self, *args, **kwargs):
        super(MySetPasswordForm, self).__init__(*args, **kwargs)
        self.fields['new_password1'].validators.append(validate_password_strength)
走野 2024-10-28 06:47:36

我只需安装 django-passwords 并让它为您处理它: https://github.com/dstufft /django-passwords

之后,您可以简单地对注册表进行子类化,并将该字段替换为 PasswordField。

I'd just install django-passwords and let that handle it for you: https://github.com/dstufft/django-passwords

After that you can simply subclass the registration form and replace the field with a PasswordField.

坏尐絯 2024-10-28 06:47:36

我认为你应该编写自己的验证器(或使用 RegexValidator,请参阅: http:// docs.djangoproject.com/en/dev/ref/validators/ )如果您使用表单或编写一些其他脚本检查正则表达式。这应该是一个简单的任务。另外,我不认为有任何内置机制,只是因为每个人对“强密码”概念的理解有点不同。

I think you should just write your own validator ( or use RegexValidator, see: http://docs.djangoproject.com/en/dev/ref/validators/ ) if you use forms or write some other script checking for regular expressions. This should be a simple task. Also I don't think there is any builtin mechanism, simply because each person understands the concept of "strong password" a little bit different.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文