Spring Security - BcryptPasswordEncoder

java spring spring-security

2279 просмотра

1 ответ

146 Репутация автора

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.

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.

My configuration from 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.

Автор: Udaya Vani Источник Размещён: 31.03.2016 04:22

Ответы (1)


6 плюса

30617 Репутация автора

Решение

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

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

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!");
}
Автор: Ali Dehghani Размещён: 31.03.2016 08:27
Вопросы из категории :
32x32