Spring Security - BcryptPasswordEncoder [英] Spring Security - BcryptPasswordEncoder

查看:45
本文介绍了Spring Security - BcryptPasswordEncoder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的应用程序中使用 Spring 安全性,并希望使用存储在数据库中的密码验证用户输入以更改密码选项.

I use Spring security in our Application and would like to validate user input with the password stored in the DB for the change password option.

密码在DB中的存储方式如下.

The password is stored as follows in DB.

user.setPassword(new BCryptPasswordEncoder().encode("<userPassword>"));

这里用户输入的密码使用上述逻辑进行编码并存储在数据库中.现在我只是想从用户那里获取密码以更改密码.从用户那里获得密码后,我使用上述逻辑进行编码并尝试与数据库进行比较.即使我使用相同的编码逻辑,编码值似乎也不同.

Here the user entered password is encoded using the above logic and stored in the DB. Now I am just trying to get password from user for change password. After getting the password from user I encode using the above logic and try to compare with the DB. The encoded value seems to be different even I use the same logic for encoding.

我在 WebSecurityConfig 中的配置:

@Autowired
public void configAuthentication(final AuthenticationManagerBuilder auth) throws Exception {

    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());

}

我不确定比较有什么问题.

I am not sure what is wrong with comparison.

推荐答案

即使我使用相同的逻辑,编码值似乎也不同编码.

The encoded value seems to be different even I use the same logic for encoding.

Bcrypt 算法使用每次都不同的内置盐值.因此,是的,即使对于相同的明文,相同的编码过程也会生成不同的密文.

Bcrypt algorithm uses a built-in salt value which is different each time. So, yes even for the same Clear Text same encoding process would generate different Cipher Texts.

从用户那里获得密码后,我使用上述逻辑进行编码并尝试与数据库进行比较

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 方法:

Do not encode the Raw Password. Suppose rawPassword is the password that client gave you and encodedPassword is the encoded stored password in the database. Then, instead of encoding the rawPassword and comparing the result using String#equals, use the PasswordEncoder#matches method:

PasswordEncoder passwordEnocder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(rawPassword, encodedPassword)) {
    System.out.println("Matched!");
}

这篇关于Spring Security - BcryptPasswordEncoder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆