在 Spring Java 中动态添加用户

Add users dynamically in Spring Java

我用这段代码从我的数据库中添加可以进行身份​​验证的用户,但问题是这段代码只执行一次,我想让用户注册我该如何实现? 我有这个解决方案 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();
        }

    }

您可以简单地设置另一个 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=?");
 }

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