How can I add users to the inMemoryAuthentication builder after it has been built?

后端 未结 2 789
后悔当初
后悔当初 2020-12-23 18:17

I have managed to load all the users into the AuthenticationManagerBuilder during the initial load of the application, but I have a requirement to add users post-startup.

相关标签:
2条回答
  • 2020-12-23 19:10

    I changed this code:

    inMemoryUserDetailsManager.createUser(new User(username, password, new ArrayList<GrantedAuthority>()));
    

    from @geoend´s answer to:

    inMemoryUserDetailsManager.createUser(User.withUsername(username).password(password).roles("USER").build());
    

    because by default, a new user doesn't have any permissions.

    0 讨论(0)
  • 2020-12-23 19:13

    The following code will do what you are asking:

    @Configuration
    @EnableWebMvcSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //whatever here
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(inMemoryUserDetailsManager());
        }
    
        @Bean
        public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
            final Properties users = new Properties();
            users.put("user","pass,ROLE_USER,enabled"); //add whatever other user you need
            return new InMemoryUserDetailsManager(users);
        }
    
    }
    

    Using the InMemoryUserDetailsManager you configured above a super simple controller that just adds and checks for the existence of a user would look like:

    @RestController
    @RequestMapping("user")
    public class SimpleSecurityController {
    
        private final InMemoryUserDetailsManager inMemoryUserDetailsManager;
    
        @Autowired
        public SimpleSecurityController(InMemoryUserDetailsManager inMemoryUserDetailsManager) {
           this.inMemoryUserDetailsManager = inMemoryUserDetailsManager;
        }
    
        @RequestMapping("exists/{username}")
        public boolean userExists(@PathVariable("username") String username ) {
            return inMemoryUserDetailsManager.userExists(username);
        }
    
        @RequestMapping("add/{username}/{password}")
        public String add(@PathVariable("username") String username, @PathVariable("password") String password) {
            inMemoryUserDetailsManager.createUser(new User(username, password, new ArrayList<GrantedAuthority>()));
            return "added";
        }
    }
    

    Also note that if you are using Spring Boot's autoconfiguration you will need to add

    @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
    

    to prevent Spring Boot from trying to autoconfigure security

    Update As noted by @AdamMichalik, @EnableWebMvcSecurity is deprecated and should be replaced by @EnableWebSecurity

    0 讨论(0)
提交回复
热议问题