Spring Security 自定义密码强度规则

1. 概述

在本快速教程中,我们将了解如何在注册期间实施和显示正确的密码限制。比如——密码应该包含一个特殊字符,或者它应该至少有 8 个字符长。

我们希望能够使用强大的密码规则——但我们不想实际手动实施这些规则。所以,我们要利用好成熟的Passay库

2. 自定义密码约束

首先 - 让我们创建一个自定义约束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 {};

}

并在UserDto中使用它:

@ValidPassword
private String password;

3. 自定义密码验证器

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

我们将创建密码验证器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;
    }
}

请注意我们如何在此处创建新的约束违规并禁用默认违规 - 以防密码无效。

最后,我们还要将Passay库添加到我们的 pom 中:

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

关于一些历史信息,Passay 是古老的vt-password Java 库的后代。

4. JS密码表

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

我们将使用一个简单的 jQuery 插件——用于 Twitter Bootstrap的 jQuery 密码强度计——在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. 结论

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值