I am using BCryptPasswordEncoder in order to encrypt a users registration and login.
The registration part works fine, it puts a new user into the database with a password such as:
'$2a$10$aUk/26idLhSaNmhNRTRejd03FnxxLxv6X0Uo0P4PcA4mbyy.
When I come to login, the username entered matches and I successfully find a user from the repository.
I am then told that the username or password is wrong. When I remove this encryption away from the program it works fine. So essentially I am doing something wrong when comparing the encrypted passwords.
Here is my UserDetailsService implementation logic:
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
System.out.println(username);
User user = userRepository.findByUsername(username);
System.out.println(user.getPassword());
if (user.getUsername().isEmpty()) {
throw new UsernameNotFoundException(
"No user found with username: "+ username);
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new org.springframework.security.core.userdetails.User
(user.getUsername(),
user.getPassword().toLowerCase(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked,
getAuthorities(Arrays.asList("ROLE_USER")));
}
private static List<GrantedAuthority> getAuthorities (List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
I also set up the beans in the web security file:
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
What am i doing wrong? Thanks.
Unless you have a non-default configuration set up, the BCryptPasswordEncoder should be saving your users passwords to the database encrypted (which it looks to be functioning properly). You shouldn't be calling #toLowerCase()
on an encrypted password since it completely changes the encryption.
The code posted doesn't appear to do any comparison.
If you are using a manual means of checking if the passwords match, you should instead use the BCryptPasswordEncoder.matches
method. It takes a non-encrypted password and then a salted hash (encrypted password) and then tells you if they are equals via a boolean return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With