java - Spring 安全-BcryptPasswordEncoder

标签 java spring spring-security

我在我们的应用程序中使用 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/

相关文章:

java - 依赖注入(inject) : should dependent objects passed as constructor args or not?

java - 当我尝试运行一个简单的 Spring 项目时出现错误

spring - Spring Boot 安全中的 HTTP 403 禁止错误

spring - SpringSession的作用是什么?

java - Spring-Security 3/Spring MVC 和可怕的@Secured/RequestMapping

java - 桌面上的 libgdx - 确定鼠标是否在窗口外

java - 迭代结果集键 - 这可能吗?

grails - Grails安全插件问题

java - 如何在 Windows 中同时安装 Android Studio 和 Appcelerator Titanium?

spring - 如何解决 java.lang.NoClassDefFoundError : com/fasterxml/classmate/TypeResolver while running spring boot app