@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return new CustomUserDetails(repository.findByUsername(username)); } };
@Component public class SecUserDetailsService implements UserDetailsService{ @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { /*Here add user data layer fetching from the MongoDB. I have used userRepository*/ User user = userRepository.findByUsername(username); if(user == null){ throw new UsernameNotFoundException(username); }else{ UserDetails details = new SecUserDetails(user); return details; } } }
@Service public class UserService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException(username); } return user; } }
public class CustomAuthenticationProvider implements AuthenticationProvider { private LdapTemplate ldapTemplate; private UserRepository userRepository; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); boolean success = ldapTemplate.authenticate(...); if (!success) { throw new BadCredentialsException("Wrong username or password"); } User user = userRepository.findByUsername(username); if (user == null) { throw new BadCredentialsException("Username not known by the application"); } return new CustomAuthentication(username, user.getRoles()); } }