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: