UserDetailsService is the Spring Security contract that tells authentication how to retrieve a user’s details. Its single operation, loadUserByUsername(String username), returns UserDetails for a unique username or throws UsernameNotFoundException. section 3.1 section 3.3.1
Use the contract to connect user management with authentication:
- Let AuthenticationProvider request user details while checking credentials with a PasswordEncoder. section 2.2 section 3.1
- Return a UserDetails object containing the username, password, authorities, and account-status information Spring Security needs. section 3.1
- Implement only retrieval when authentication is required; use UserDetailsManager when the application must create, modify, or delete users. section 3.1 section 3.4
- Choose an implementation such as InMemoryUserDetailsManager, JdbcUserDetailsManager, or LdapUserDetailsManager according to the user store. section 3.4
A small in-memory implementation
Create a UserDetailsService bean with an in-memory user, then register it with Spring Security. The user builder supplies the username, password, and authority. InMemoryUserDetailsManager is useful for examples and proofs of concept, but its in-memory storage is not intended for production-ready applications. section 2.3.1
Custom retrieval logic
Implement UserDetailsService around a user list, database, or another system. Search for the requested username and return the matching UserDetails; otherwise throw UsernameNotFoundException. Register the implementation as a bean and test an authenticated endpoint with curl. section 3.3.2
Figure 3.1 Spring Security’s authentication flow. The AuthenticationFilter captures the incoming request and passes the task of authentication to the AuthenticationManager. The AuthenticationManager, in turn, utilizes an authentication provider to carry out the authentication process. For verifying the username and password, the AuthenticationProvider relies on a UserDetailsService and a PasswordEncoder.
Follow the authentication flow from AuthenticationFilter through AuthenticationManager and AuthenticationProvider to UserDetailsService and PasswordEncoder. section 3.1
Testing with configured users
Use @WithUserDetails("john") when a test should authenticate with a user supplied by a UserDetailsService. This approach exercises integration with the configured user data source rather than creating a mock user. section 18.2

