我正在为这个而烦恼。我有一个像这样的简单用户实体
@Entity
public class User {
private static final PasswordEncoder pwEncoder = new BCryptPasswordEncoder();
@Id
@GeneratedValue
private long id;
@NotNull(message = "FIELD_IS_NULL")
@NotEmpty(message = "FIELD_IS_REQUIRED")
@Length(min = 3, message = "FIELD_MUST_HAVE_AT_LEAST_3_CHARACTERS")
private String username;
@NotNull(message = "FIELD_IS_NULL")
@NotEmpty(message = "FIELD_IS_REQUIRED")
@Length(min = 6, message = "FIELD_MUST_HAVE_AT_LEAST_6_CHARACTERS")
@Pattern(regexp = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,128}$", message="PW_MIN_6_MAX_128_1_UPPER_1_LOWER_1_NUMERIC")
private String password;
public User(String username, String password){
this.username = username;
this.password = pwEncoder.encode(password);
}
/* getters and setters */
}
这工作正常,除了密码散列发生在任何验证之前,这意味着验证散列密码而不是未散列密码。
我正在使用 PagingAndSortingRepository
来满足我所有的存储库需求,我真的很想避免只为这种情况实现 Controller 。
我觉得我在那里错过了一些非常重要的东西......
最佳答案
如果你使用这个构造函数
public User(String username, String password){
this.username = username;
this.password = pwEncoder.encode(password);
}
您将拥有编码密码而不是原始值
你可以像这样创建@PrePersist 方法:
@PrePersist
public void prePersist(){
password = pwEncoder.encode(password);
}
关于Java Spring 散列和验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038701/