知識庫 / Spring / Spring Security RSS 訂閱

密碼註冊 – 強度與規則

Spring Security
HongKong
5
02:56 PM · Dec 06 ,2025
該文章是系列的一部分
• Spring Security 註冊系列
• 使用 Spring Security 的註冊過程
• 通過電子郵件激活新賬户
• Spring Security 註冊 – 發送驗證郵件
• 使用 Spring Security 註冊 – 密碼編碼
• 註冊 API 變為 RESTful
• 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 {};

}

並在 中使用它:

@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 插件——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. 結論

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

下一頁 »
更新您的密碼
返回上一頁 «
Spring Security – 重置您的密碼
user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.