使用Spring Security进行身份验证

时间:2020-07-10 10:14:02

标签: java spring-boot spring-security

在Spring Security中使用身份验证时,我有些困惑。身份验证有两种方式。

  1. 通过覆盖配置方法
  2. 通过为AuthenticationProvider实现bean实例

我需要知道它们与使用它们的优缺点之间的区别。

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 个答案:

答案 0 :(得分:2)

  • 如果不确定弹簧安全性过滤器链,请参见此答案。 How Spring Security Filter Chain works

  • 这是我最近在设置演示ldap +内存身份验证时拍摄的屏幕截图。

    enter image description here

  • 如您所见,最后,我们希望在Spring Security过滤器链中使用AuthenticationFilter类型。该过滤器负责接收登录请求并确定身份验证是否成功。

  • AuthenticationFilter引用了AuthenticationManger,并且AuthenticationManger实现(称为ProviderManager)不直接进行身份验证。相反,AuthenticationManger实现可以具有AuthenticationProvider的列表并取决于类型身份验证请求,它要求列表中的相应AuthenticationProvider进行身份验证。

  • AuthenticationFilter委托给AuthenticationManger(。ProviderManager),后者又委托给one的{​​{1}}

  • 所以这是示例。仅出于演示目的,我将复制您的AuthenticationProvider定义,并查看 authenticationProvider() .ie AuthenticationManger的外观

ProviderManager

enter image description here

注意

我在这里做了一些简化。实际上 @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; } 也可以有父母。但实际上,它具有提供商列表。参见https://spring.io/guides/topicals/spring-security-architecture

enter image description here