79206246

Date: 2024-11-20 07:52:12
Score: 0.5
Natty:
Report link

The issue is probably coming from code in LoginController while login: Authentication authentication = this.authenticationManager.authenticate(login);

AuthenticationManager.authenticate(..) further calls UserDetailsService.loadUserByUsername(..) in its implementation to check whether the user exists.

Try creating a new Service class that implements UserDetailsService interface and implements loadUserByUsername(..) method. This is because you want Spring Security to verify the username from your database.

Here is the sample code:

@Service
public class MyUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    @Autowired
    public MyUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> userOptional = this.userRepository.findByUsername(username);

        if(userOptional.isEmpty()) {
            throw new UsernameNotFoundException(String.format("No user exists with username %s", username));
        }

        User user = userOptional.get();

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUserName())
                .password(user.getPassword())
                .roles(String.valueOf(user.getRole()))
                .build();
    }
}

So, spring security will come to this service implementation class to execute the method loadUserByUsername(..).

Let me know if this solves your problem.

References:

  1. https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetailsService.html
  2. https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/user-details-service.html
Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Aditya Kumar Mallik