我想為注冊密碼的用戶添加模式匹配。在我的用戶模型中,我有:
@Column
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]{8,}$")
private String password;
但是,當我去注冊用戶時,我收到了 400 Bad Request。
javax.validation.ConstraintViolationException: Validation failed for classes [com.practice.models.AppUser] during persist time for groups [javax.validation.groups.Default, ]\nList of constraint violations:[\n\tConstraintViolationImpl{interpolatedMessage='must match \"^(?=.*[A-Za-z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!%*#?&]{8,}$\"', propertyPath=password, rootBeanClass=class com.practice.models.AppUser, messageTemplate='{javax.validation.constraints.Pattern.message}'}\n]\n\tat
可以用@Pattern注解完成嗎?它應該繼續模型嗎?
我的控制器的端點如下所示:
@PostMapping("/register")
public AppUser register(@Valid @RequestBody AppUser user) {
return appUserService.createUser(user);
}
這是我發送給注冊的資料:
{
"username": "Johnny",
"email": "[email protected]",
"password": "P@ssword123",
"passwordConfirmation": "P@ssword123"
}
然后在我的服務層,我用 BCrypt 加密我的密碼:
public AppUser createUser(AppUser appUser) {
Optional<AppUser> existingUser = appUserRepo.findByUsername(appUser.getUsername());
if (existingUser.isPresent()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "A user with that username already exists");
}
if (!appUser.getPassword().equals(appUser.getPasswordConfirmation())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Passwords don't match");
}
String encodedPassword = bCryptPasswordEncoder.encode(appUser.getPassword());
appUser.setPassword(encodedPassword);
return appUserRepo.save(appUser);
}
```
uj5u.com熱心網友回復:
正則運算式有點偏離,您應該使用\\d而不是\\\\d:
^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$
uj5u.com熱心網友回復:
當您在密碼驗證的同時使用密碼加密時,通常會發生這種情況。基本上,您的應用程式當前正在針對加密密碼運行模式驗證。
如果沒有額外的配置,@Pattern注釋會導致驗證不僅在您@Valid在控制器中使用的地方運行,而且在您呼叫appUserRepo.save(appUser). 這意味著模式匹配是針對散列密碼運行的,這很可能與您的模式不匹配。
如果您不想持久運行驗證,請將此行添加到您的application.properties檔案中:
spring.jpa.properties.javax.persistence.validation.mode=none
uj5u.com熱心網友回復:
使用以下正則運算式來滿足以下條件:
狀況:
- 最少 1 個大寫字母。
- 最少 1 個小寫字母。
- 最少 1 個特殊字符。
- 最少 1 個號碼。
- 最少 8 個字符。
正則運算式:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$@!%&*?])[A-Za-z\d#$@!%&*?]{8,}$
uj5u.com熱心網友回復:
測驗您的正則運算式,它似乎不起作用。我能夠快速找到以下密碼的正則運算式示例。
^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s:])([^\s]){8,16}$
僅當以下所有條件都為真時,此正則運算式才匹配:
- 密碼必須包含 1 個數字 (0-9)
- 密碼必須包含 1 個大寫字母
- 密碼必須包含 1 個小寫字母
- 密碼必須包含 1 個非字母數字
- 密碼為 8-16 個字符,無空格
https://regex101.com/library/0bH043
這是另一個從字串構建正則運算式的好網站:https : //regex-generator.olafneumann.org/
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355781.html
