UserDetailsService is a Spring Security interface for retrieving a user's authentication details. Its single loadUserByUsername() method accepts a username and returns UserDetails, or throws UsernameNotFoundException when no user exists. section 5.2
Choose an implementation according to where application user records are kept:
- Use InMemoryUserDetailsManager when a small, stable set of users is sufficient, such as testing or a very simple application. section 5.2.1
- Use a JDBC or LDAP user store when authentication data belongs in those external systems. section 5.2
- Create a custom implementation when the application's security needs require a different user store, such as a database repository. section 5.2 section 5.2.2
Loading registered users from a repository
A database-backed service can receive UserRepository and delegate lookup to findByUsername(). Return the User when found; otherwise throw UsernameNotFoundException because loadUserByUsername() must never return null. Since the interface has one method, a lambda can define the bean. section 5.2.2
Listing 5.4 Defining a custom user details service bean
@Bean
public UserDetailsService userDetailsService(UserRepository userRepo) {
return username -> {
User user = userRepo.findByUsername(username);
if (user != null) return user;
throw new UsernameNotFoundException("User '" + username + "' not found");
};
}
Browse the complete custom UserDetailsService bean that connects Spring Security authentication to UserRepository. section 5.2.2

