Registration – Password Strength and Rules – 注册 – 密码强度和规则

最后修改: 2015年 4月 4日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll look at how to implement and show proper password constraints during registration. Things like – the password should contain a special character, or it should be at least 8 characters long.

在这个快速教程中,我们将看看如何在注册时实现和显示正确的密码约束。诸如–密码应该包含一个特殊字符,或者至少应该有8个字符。

We want to be able to use powerful password rules – but we don’t want to actually implement these rules manually. So, we’re going to make good use of the mature Passay library.

我们希望能够使用强大的密码规则–但我们不希望实际手动实现这些规则。因此,我们要好好利用成熟的Passay库

2. Custom Password Constraint

2.自定义密码约束

First – let’s create a custom constraint ValidPassword:

首先,让我们创建一个自定义约束ValidPassword

@Documented
@Constraint(validatedBy = PasswordConstraintValidator.class)
@Target({ TYPE, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface ValidPassword {

    String message() default "Invalid Password";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

And use it in the UserDto:

并在UserDto中使用它。

@ValidPassword
private String password;

3. Custom Password Validator

3.自定义密码验证器

Now – let’s use the library to create some powerful password rules without having to actually manually implement any of them.

现在–让我们使用这个库来创建一些强大的密码规则,而不需要实际手动实现任何规则。

We’ll create the password validator PasswordConstraintValidator – and we’ll define the rules for the password:

我们将创建密码验证器PasswordConstraintValidator – 我们将定义密码的规则。

public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword, String> {

    @Override
    public void initialize(ValidPassword arg0) {
    }

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {
        PasswordValidator validator = new PasswordValidator(Arrays.asList(
           new LengthRule(8, 30), 
           new UppercaseCharacterRule(1), 
           new DigitCharacterRule(1), 
           new SpecialCharacterRule(1), 
           new NumericalSequenceRule(3,false), 
           new AlphabeticalSequenceRule(3,false), 
           new QwertySequenceRule(3,false),
           new WhitespaceRule()));

        RuleResult result = validator.validate(new PasswordData(password));
        if (result.isValid()) {
            return true;
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(
          Joiner.on(",").join(validator.getMessages(result)))
          .addConstraintViolation();
        return false;
    }
}

Notice how we’re creating the new constraint violation here and disabling the default one as well – in case the password is not valid.

请注意,我们在这里创建了新的违规约束,同时也禁用了默认的约束–以防密码无效。

Finally, let’s also add the Passay library into our pom:

最后,让我们也把Passay库加入我们的pom。

<dependency>
	<groupId>org.passay</groupId>
	<artifactId>passay</artifactId>
	<version>1.0</version>
</dependency>

For a bit of historical info, Passay is the descendant of the venerable vt-password Java library.

对于一些历史信息,Passay是古老的vt-passwordJava库的后裔。

4. JS Password Meter

4.JS密码表

Now that the server side is done, let’s take a look at the client side and implement a simple Password Strength” functionality with JavaScript.

现在服务器端已经完成,让我们看一下客户端,用JavaScript实现一个简单的密码强度“功能

We’ll use a simple jQuery plugin – jQuery Password Strength Meter for Twitter Bootstrap – to show the password strength in registration.html:

我们将使用一个简单的jQuery插件 – jQuery Password Strength Meter for Twitter Bootstrap – 来显示registration.html中的密码强度。

<input id="password" name="password" type="password"/>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="pwstrength.js"></script>                  
<script type="text/javascript">
$(document).ready(function () {
    options = {
        common: {minChar:8},
        ui: {
            showVerdictsInsideProgressBar:true,
            showErrors:true,
            errorMessages:{
                wordLength: '<spring:message code="error.wordLength"/>',
                wordNotEmail: '<spring:message code="error.wordNotEmail"/>',
                wordSequences: '<spring:message code="error.wordSequences"/>',
                wordLowercase: '<spring:message code="error.wordLowercase"/>',
                wordUppercase: '<spring:message code="error.wordUppercase"/>',
                wordOneNumber: '<spring:message code="error.wordOneNumber"/>',
                wordOneSpecialChar: '<spring:message code="error.wordOneSpecialChar"/>'
            }
        }
    };
    $('#password').pwstrength(options);
});
</script>

5. Conclusion

5.结论

And that’s it – a simple but very useful way to show the strength of the password on the client side and enforce certain password rules on the server side.

就是这样–一个简单但非常有用的方法,在客户端显示密码的强度,并在服务器端强制执行某些密码规则。

The full implementation of this tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

本教程的完整实现可以在github 项目中找到 – 这是一个基于 Eclipse 的项目,因此应该很容易导入并按原样运行。

Next »

Updating your Password

« Previous

Spring Security – Reset Your Password