我想哈希&使用bcrypt和Spring安全性的用户密码。
这是我的用户模型(我删除了无用的代码):
public class User {
private Integer id;
private String email;
private String hashedPassword;
private String salt; //I want to use this salt.
private Boolean enabled;
//Getters & Setters
}
以下是我使用自己的盐创建新用户的方法:
@Transactional
public User create(String email, String password) {
User user = new User();
user.setSalt(BCrypt.gensalt(12)); //Generate salt
user.setEnabled(true);
user.setEmail(email);
user.setHashedPassword(BCrypt.hashpw(password, user.getSalt()));
return dao.persist(user);
}
这是弹簧配置:
<beans:bean id="userService" class="com.mycompany.service.UserService"/>
<beans:bean id="myCustomUserDetailService" class="com.mycompany.service.MyCustomUserDetailService"/>
<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
<beans:property name="userPropertyToUse" value="salt"/>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="myCustomUserDetailService">
<password-encoder ref="bcryptEncoder">
<salt-source ref="saltSource"/>
</password-encoder>
</authentication-provider>
</authentication-manager>
在此配置中,我指出PasswordEncoder
必须使用User.getSalt()
;
问题:我收到以下错误500 :
与crypto模块PasswordEncoder一起使用时,salt值必须为null。
在查看stackoverflow之后,似乎salt必须为null,因为BCryptPasswordEncoder使用自己的SaltSource。
SaltSource
? OR SaltSource
?感谢。
答案 0 :(得分:1)
回答第一个问题:
BCryptPasswordEncoder有hardcoded盐源(Bcrypt.getsalt) 因此不可能强制BCryptPasswordEncoder使用其他盐源 不过,您可以尝试将其子类化,并添加自定义salt属性。