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

    }

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I used the first solution for simplicity :) thank you
Good choice, since that has the advantage of keeping the whole "Find user" logic in one place, the UserRepository. The JDBC solution tends to duplicate it, which makes it harder to maintain if something changes.
hi does jdbc solution update new roles dynamically ?
Not sure, but honestly, I doubt it. When should it do so? It would have to guess - or send dozens of role requests to the database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.