Аутентификация с помощью Spring Security - PullRequest
1 голос
/ 10 июля 2020

У меня некоторая путаница при работе с аутентификацией в Spring Security. Существует два способа аутентификации.

  1. Путем переопределения метода настройки
  2. Путем реализации экземпляра bean-компонента для AuthenticationProvider

Мне нужно знать, в чем разница между ними и преимуществами и недостатками использования каждого из них.

1.

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {    
    auth.userDetailsService(userDetailsService);
}

@Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder(){
    return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
     DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
     daoAuthenticationProvider.setUserDetailsService(userDetailsService);
     daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
     return daoAuthenticationProvider;
}

1 Ответ

2 голосов
/ 10 июля 2020
  • Если вы не уверены в цепи пружинного фильтра, см. Этот ответ. Как работает Spring Security Filter Chain

  • Вот скриншот, который я недавно сделал, когда настраивал демо ldap + аутентификацию в памяти.

    enter image description here

  • As you can see, in the end, we want a type of AuthenticationFilter in our spring security filter chain. That filter is responsible for receiving the login request and decide the if authentication successful or not.

  • AuthenticationFilter has a reference to AuthenticationManger and AuthenticationManger implementation (which is called ProviderManager) does not do authentication directly. Instead AuthenticationManger implementations can have a list of AuthenticationProviders and depend on the type authentication request, it asks the corresponding AuthenticationProvider in its list do the authentication.

  • AuthenticationFilter delegates to AuthenticationManger (.ie ProviderManager) which in turn delegates to one of AuthenticationProvider

  • So here is sample. Just for demo purpose, I am duplicating your authenticationProvider() definition and see how the AuthenticationManger .ie ProviderManager looks

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider1())
            .authenticationProvider(authenticationProvider2());
    }

    @Bean("my-auth-provider-1")
    public AuthenticationProvider authenticationProvider1(){
        DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        return provider;
    }

    @Bean("my-auth-provider-2")
    public AuthenticationProvider authenticationProvider2(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        return provider;
    }
  

enter image description here

Note

I have simplified a bit here. Actually ProviderManager can have parent too. But effectively it has a list of providers. See https://spring.io/guides/topicals/spring-security-architecture

введите описание изображения здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...