在Spring Java中动态添加用户

时间:2016-05-04 23:48:55

标签: spring spring-data spring-data-rest

我用这个代码来添加我的数据库中的用户可以进行身份​​验证,但是这个代码执行一次的问题,我希望有用户注册我该如何实现呢? 我有这个解决方案How to adding new user to Spring Security in runtime但我不能将它添加到我的实际代码中请帮忙。 这是我的代码

@Configuration
    @EnableWebSecurity
    protected static class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        DataSource dataSource;

        @Autowired
        UserRepository userRepository;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            for (UsersEntity user : userRepository.findAll())
                if (user.getUsername() != null && user.getPassword() != null)
                    auth.
                            inMemoryAuthentication()
                            .passwordEncoder(UsersEntity.ENCODE_PASS)
                            .withUser(user.getUsername()).password(user.getPassword())
                            .roles("USER");
        }


        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean()
                throws Exception {
            return super.authenticationManagerBean();
        }

    }

1 个答案:

答案 0 :(得分:2)

您只需设置另一个authenticationProvider

@Autowired
private MyAuthenticationProvider authenticationProvider;

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
}

只需实施您自己的MyAuthenticationProvider,就每次登录尝试都会询问您的UserRepository。或者另一种方法是简单地使用基本的jdbc:

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.jdbcAuthentication().dataSource(dataSource)
  .usersByUsernameQuery(
  "select username,password, enabled from users where username=?")
  .authoritiesByUsernameQuery(
  "select username, role from user_roles where username=?");
 }

...当然,您需要在那里设置自己的查询。