InMemoryUserDetailsManager is a Spring Security implementation of UserDetailsService and UserDetailsManager that keeps application users in memory for authentication. It can replace Spring Boot’s default UserDetailsService with explicitly managed credentials, but it is intended for examples and proofs of concept rather than production applications. section 2.3.1 section 2.4
Configure the manager by defining users and exposing it as a bean:
- Create users with User.withUsername(), password(), authorities(), and build(). section 2.3.1
- Pass one or more UserDetails objects to the manager constructor, or create users on an empty manager with createUser(). section 2.3.1 section 7.1.1
- Pair the setup with a PasswordEncoder; NoOpPasswordEncoder enables cleartext example passwords but is not production-ready. section 2.3.1 section 2.4
- Use authorities with endpoint authorization rules such as hasAuthority() or hasAnyAuthority() to control access after authentication. section 7.1.1
Two in-memory users
A configuration can register John with READ authority and Jane with WRITE authority, then restrict every endpoint with hasAuthority("WRITE"). Jane’s authenticated request succeeds, while John receives HTTP 403 Forbidden. section 7.1.1
Listing 2.4 Creating a user with the User builder class for UserDetailsService
@Configuration
public class ProjectConfig {
@Bean
UserDetailsService userDetailsService() {
var user = User.withUsername("john") #1
.password("12345") #1
.authorities("read") #1
.build(); #1
return new InMemoryUserDetailsManager(user); #2
}
}
Browse the compact Java configuration that builds a user and supplies it to InMemoryUserDetailsManager. section 2.3.1
