首页 > 解决方案 > 使用 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;
}

标签: javaspring-bootspring-security

解决方案


  • 如果您不确定弹簧安全过滤器链,请参阅此答案。Spring Security 过滤器链是如何工作的

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

    在此处输入图像描述

  • 如您所见,最后,我们希望AuthenticationFilter在我们的 spring 安全过滤器链中添加一个类型。该过滤器负责接收登录请求并决定身份验证是否成功。

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

  • AuthenticationFilter委托给AuthenticationManger(.ie ProviderManager),后者又委托给oneof AuthenticationProvider

  • 所以这里是样本。仅出于演示目的,我正在复制您的 authenticationProvider()定义并查看AuthenticationManger.ie的ProviderManager外观

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

在此处输入图像描述

笔记

我在这里简化了一点。其实ProviderManager也可以有父母。但实际上它有一个提供者列表。见https://spring.io/guides/topicals/spring-security-architecture

在此处输入图像描述


推荐阅读