Spring Security 为什么Spring密码验证器不起作用?

r8uurelv  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(138)

我想做一个密码验证器,其中密码应该至少有1个大写,1个小写和1个特殊,没有空格。我通过 Postman 密码“123”,我得到了Http 200. OK,但我不应该,因为它违反了我的密码验证器。下面是我的代码:Dto请求:

@Data
@AllArgsConstructor
public class UserRegistrationDtoRequest {
    @NotNull
    private String email;
    @ValidPassword
    private String password;
    
    private String address;

}

字符串
有效密码注解:

@Documented
@Constraint(validatedBy = PasswordConstraintValidator.class)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidPassword {
    String message() default "Invalid password.Password should have at least 8 characters";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

}


ConstraintValidator实现:

public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword,String> {
    @Override
    public void initialize(ValidPassword constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        PasswordValidator validator = new PasswordValidator(Arrays.asList(
                new LengthRule(8,20),
                new CharacterRule(EnglishCharacterData.UpperCase,1),
                new CharacterRule(EnglishCharacterData.LowerCase,5),
                new CharacterRule(EnglishCharacterData.Special,1),
                new WhitespaceRule()));
        RuleResult ruleResult = validator.validate(new PasswordData(value));
        if(ruleResult.isValid()){
            return true;
        }
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(
                validator.getMessages(ruleResult).toString()).addConstraintViolation();
        return false;
    }
}

vpfxa7rd

vpfxa7rd1#

Sping Boot 验证使用javax提供的@Valid注解。

@PostMapping("${endpoint.api.signup}")
  public ResponseEntity<Boolean> signup(@RequestBody @Valid UserRegistrationDtoRequest registrationDTO) {
    log.info("Request to register user: {}", registrationDTO.getUsername());
    userService.register(registrationDTO);
    return ResponseEntity.ok(true);
  }

字符串

相关问题