Custom WebSecurityConfigurerAdapter

后端 未结 3 2134
时光说笑
时光说笑 2021-02-06 05:38

I have this problem implementing a custom login authentication using SpringBoot and SpringBoot-Security. I made a Bitbucket repository as reference for this thread (within Custo

3条回答
  •  孤城傲影
    2021-02-06 05:40

    Firstly I would encourage you to read about String Security Core Services.

    A key one in this situation is AuthenticationManager that is responsible for deciding if the user is authenticated or not. This is what you configure with AuthenticationManagerBuilder. It's primary implementation in Spring is ProviderManager that allows to define multiple authentication mechanisms in a single applications. The most common use case is that there is one, but it is still handled by this class. Each of those multiple authentication mechanisms is represented by a different AuthenticationProvider. ProviderManager takes a list of AunthenticationProviders an iterates through them to see if any of them can authenticate the user.

    What you are interested in is DaoAuthenticationProvider. As the name suggests, it allows to use a Data Access Object to authenticate the user. It uses a standard interface for such DAO - a UserDetailsService. There is a default implementation available in Spring Security, but usually this is the bit you will want to implement yourself. All the rest is provided.

    Also, the configuration bit you need is totally independent from Spring Boot. This is how you'd do it in XML:

    
        
    
    

    And in Java it will be:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserDetailsService myUserDetailsService;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(myUserDetailsService);
        }
    }
    

    As per UserDetails implementation, usually the one provided by Spring Security is enough. But you can also implement your own if need be.

    Usually you will also want a PasswordEncoder. A good one, like BCryptPasswordEncoder:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserDetailsService userDetailsService;
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);
        }
    }
    

    Notice that it's a @Bean, so that you can @Autowire it in your UserRepository to encode user passwords as you save them in the database.

提交回复
热议问题