使用 Spring Data REST 进行密码编码 [英] Password encoding with Spring Data REST
问题描述
我应该如何使用 Spring Data REST 自动编码我的实体提交的纯密码字段?
How should I encode automatically the subbmitted plain password field of my entity with Spring Data REST?
我正在使用 BCrypt 编码器,我想在客户端通过 POST、PUT 和 PATCH 发送请求时自动编码请求的密码字段.
I'm using BCrypt encoder and I want to automatically encode the request's password field, when the client send it via POST, PUT and PATCH.
@Entity
public class User {
@NotNull
private String username;
@NotNull
private String passwordHash;
...
getters/setters/etc
...
}
首先我尝试使用@HandleBeforeCreate 和@HandleBeforeSave 事件侦听器来解决,但它的参数中的用户已经合并,所以我无法区分用户的新密码或旧密码哈希:
First I tried to solve with @HandleBeforeCreate and @HandleBeforeSave event listeners but the User in it's argument is already merged, so I can't make any difference between the User's new password, or the old passwordHash:
@HandleBeforeSave
protected void onBeforeSave(User user) {
if (user.getPassword() != null) {
account.setPassword(passwordEncoder.encode(account.getPassword()));
}
super.onBeforeSave(account);
}
是否可以在 setter 方法上使用 @Projection 和 SpEL?
Is that possible, to use @Projection and SpEL on a setter method?
推荐答案
你可以实现一个 Jackson JsonDeserializer:
public class BCryptPasswordDeserializer extends JsonDeserializer<String> {
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(node.asText());
return encodedPassword;
}
}
并将其应用于您的 JPA 实体属性:
And apply it to your JPA Entity property:
// The value of the password will always have a length of
// 60 thanks to BCrypt
@Size(min = 60, max = 60)
@Column(name="password", nullable = false, length = 60)
@JsonDeserialize(using = BCryptPasswordDeserializer.class )
private String password;
这篇关于使用 Spring Data REST 进行密码编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!