我在我们的应用程序中使用 Spring 安全性,并希望使用存储在数据库中的密码来验证用户输入以更改密码选项。
密码在DB中存储如下
user.setPassword(new BCryptPasswordEncoder().encode("<userPassword>"));
此处用户输入的密码使用上述逻辑进行编码并存储在数据库中。现在我只是想从用户那里获取密码以更改密码。从用户那里获得密码后,我使用上述逻辑进行编码并尝试与数据库进行比较。即使我使用相同的编码逻辑,编码值似乎也不同。
我在 WebSecurityConfig
中的配置:
@Autowired
public void configAuthentication(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
我不确定比较有什么问题。
最佳答案
The encoded value seems to be different even I use the same logic for encoding.
Bcrypt 算法使用每次都不同的内置盐值。因此,是的,即使对于相同的明文,相同的编码过程也会生成不同的密文。
After getting the password from user I encode using the above logic and try to compare with the DB
不要对原始密码进行编码。假设 rawPassword
是客户端给你的密码,encodedPassword
是编码后存储在数据库中的密码。然后,不用对 rawPassword
进行编码并使用 String#equals
比较结果,而是使用 PasswordEncoder#matches
方法:
PasswordEncoder passwordEnocder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(rawPassword, encodedPassword)) {
System.out.println("Matched!");
}
关于java - Spring 安全-BcryptPasswordEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324113/