Encoded password does not look like BCrypt when using Spring Security UserDetailsService

1.7k Views Asked by At

When i am using Spring Security UserDetailsService i am encounter Encoded password does not look like BCrypt, whereas without it working fine

Otherwise its working fine

database is here enter image description here

From EmployeeServiceImpl

 @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Employee employee = employeeRepository.findByUserName(username);
        System.out.println(employee);
        if (username == null) {
            throw new UsernameNotFoundException("Invalid user name or password");
        }
         return new User(employee.getUserName(),employee.getPassword(),
                mapRolesToAuthorities(employee.getRoles()));
}
   private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles) {
        return roles.stream()
                .map(
                        role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
    }

For registration i am using BCryptPasswordEncoder

@Override
    public void save(ErmUser ermUser) {

        Employee employee = new Employee();

        // assign user details to the user object
        employee.setUserName(ermUser.getUserName());
        employee.setPassword(passwordEncoder.encode(ermUser.getPassword()));
        employee.setFirstName(ermUser.getFirstName());
        employee.setLastName(ermUser.getLastName());
        employee.setEmail(ermUser.getEmail());

        // give user role of "EMPLOYEE"
        employee.setRoles(Arrays.asList(roleRepository.findRoleByName("ROLE_EMPLOYEE")));

        // save the user in database
        employeeRepository.save(employee);
    }

https://github.com/TilmeezUrRehmanBhatti/thymeleafdemo-employees-db/issues/2

I don't think it's because of the password its somewhere in the code where we are not handling incoming passwords from the user to BCrypt and then matching, while debugging I noticed it try to match with the plain password with is entered by me(user) with BCrypt password from Database. And i don't know how to handle this or convert the input password to BCrypt because normally it's handled by spring security (If I am not wrong)

2

There are 2 best solutions below

0
Tilmeez Ur Rehman Bhatti On BEST ANSWER

This issue is related to column size. As I am using PostgreSQL, it might be of type issue.

Alter the password column type from char to varchar, it solves my problem

3
Chetan Ahirrao On

I am not sure why you got that impression. Bcrypt encoder uses Strenth parameter with value from 4 to 31 to encode the text. When it's 4, you will see hashed value something like $2a$04 and when it's 10 (default value) hash will be of pattern $2a$10
now, the question is why three passwords in the database have same hash value. Was it generated and updated outside this program?