Skip to content

5.2.1 In-memory user details service

One place where user information can be kept is in memory. Suppose you have only a handful of users, none of which are likely to change. In that case, it may be simple enough to define those users as part of the security configuration.

The following bean method shows how to create an InMemoryUserDetailsManager with two users, “buzz” and “woody,” for that purpose.

Listing 5.2 Declaring users in an in-memory user details service bean

java
@Bean
public UserDetailsService userDetailsService(PasswordEncoder encoder) {
  List<UserDetails> usersList = new ArrayList<>();
  usersList.add(new User(
    "buzz", encoder.encode("password"),
      Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))));
  usersList.add(new User(
    "woody", encoder.encode("password"),
      Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))));
  return new InMemoryUserDetailsManager(usersList);
}

Here, a list of Spring Security User objects are created, each with a username, password, and a list of one or more authorities. Then an InMemoryUserDetailsManager is created using that list.

If you try out the application now, you should be able to log in as either “woody” or “buzz,” using password as the password.

The in-memory user details service is convenient for testing purposes or for very simple applications, but it doesn’t allow for easy editing of users. If you need to add, remove, or change a user, you’ll have to make the necessary changes and then rebuild and redeploy the application.

For the Taco Cloud application, you want customers to be able to register with the application and manage their own user accounts. That doesn’t fit with the limitations of the in-memory user details service. So let’s take a look at how to create our own implementation of UserDetailsService that allows for a user store database.

Released under the MIT License.