1

This code I use to add users from my database that can authenticate but the problem this code is executed once , I want to have users that register how can I achieve that ? I have this solution How to adding new user to Spring Security in runtime but I coudn't add it to my actual code please help. this is my code

@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();
        }

    }
Community
  • 1
  • 1
AndroLife
  • 908
  • 2
  • 11
  • 27

1 Answers1

2

You can simply set another authenticationProvider.

@Autowired
private MyAuthenticationProvider authenticationProvider;

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

Simply implement your own MyAuthenticationProvider that asks your UserRepository for each login attempt. Or another way would be to simply use basic 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=?");
 }

...of course, you would need to set your own queries there.

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58