0

In my Spring Boot based app - for the sake of simplicity - I rely on the Spring Web Security auto-configuration of the InMemoryUserDetailsManager via the UserDetailsServiceAutoConfiguration.

For this purpose I've just set up a single user via properties(.yml) as follow:

spring.security.user:
  name: whatever
  password: xxx
  roles: USER

I'd just like to subsequently add extra users I might read from another source (properties or so - exact values not known at compile time), by calling the appropriate method on InMemoryUserDetailsManager i.e. createUser(UserDetails user) (inherited from interface UserDetailsManager). Basically in a @Configuration-like bean of mine:

@Autowired // Spring will inject its newly created InMemoryUserDetailsManager
private UserDetailsManager userDetailsManager;

// Maybe some annotation like @PostConstruct maybe? but should be conditioned to the existence of the above UserDetailsManager - can I do this?
public void loadMyUsers() {
    ...
    Collection<UserDetails> users; // my list of "users"/UserDetails
    users.stream().forEach(userDetailsManager::createUser);
}

I've seen this question: How can I add users to the inMemoryAuthentication builder after it has been built? but unfortunately answers lead to other directions that I'm expecting i.e. either by providing a REST endpoint to add users (1st answer), or by "hardcoding" the add of users (2nd answer).

Is it possible to do this?

maxxyme
  • 2,164
  • 5
  • 31
  • 48

1 Answers1

0

You can use ApplicationRunner or CommandLineRunner to execute some codes once Spring Boot has started and create users in these runner.

Code wise , It looks like:

@SpringBootApplication
public class MyApplication {

    @Autowired 
    private UserDetailsManager userDetailsManager;

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            User user=new User("Foo", "password", ......);
            userDetailsManager.createUser(user);
        };
    }


    public static void main(String[] args) {
        SpringApplication.run(DangerApplication.class, args);
    }

}
Ken Chan
  • 84,777
  • 26
  • 143
  • 172