密碼註冊 – 強度與規則

Spring Security
Remote
1
08:35 PM · Nov 29 ,2025

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 密碼強度計

現在服務器端已完成,讓我們來查看客户端並實現一個簡單的 密碼強度

我們將使用一個簡單的 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. 結論

這就是一個簡單但非常實用的方法,可以在客户端顯示密碼強度,並在服務器端強制執行某些密碼規則。

下一條 »
Updating Your Password
«
Previous Spring Security – Reset Your Password
user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.