liveBook · Manning

UserDetailsService

As explained in Spring in Action, Sixth Edition

UserDetailsService is a Spring Security interface that retrieves user-specific authentication details synchronously.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Defines the one-method contract and demonstrates in-memory and repository-backed implementations with missing-user handling.
Examples
Uses in-memory users named buzz and woody, then demonstrates a Taco Cloud database lookup through UserRepository.
What it assumes
Assumes basic Spring bean configuration and user persistence concepts while teaching the interface contract and lookup failure rule.
What you can do after
Build it from scratch by declaring an in-memory or repository-backed UserDetailsService bean.
How it connects
Connects UserDetails with UsernameNotFoundException, PasswordEncoder, UserRepository, and Spring Data JPA.

Also explained in

Compare how 2 books explain UserDetailsService →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.