【问题标题】:How to get the AuthenticationManager when using the AuthenticationManagerBuilder to add custom provider?使用 AuthenticationManagerBuilder 添加自定义提供者时如何获取 AuthenticationManager?
【发布时间】:2018-08-30 20:19:51
【问题描述】:

我正在使用 Spring Boot 2.0(利用 Spring Security 5.0)。我正在尝试将自定义 AuthenticationProvider 添加到我的 WebSecurityConfigurerAdapter 子类中的 AuthenticationManager 。如果我重写 configure(AuthenticationManagerBuilder) 方法来提供我的新提供程序,那么我不知道如何将 AuthenticationManager 作为 bean 检索。

例如:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    {
        auth.authenticationProvider(customAuthenticationProvider);
    }
}

customAuthenticationProvider 在哪里实现AuthenticationProvider

Spring docs中,好像指明两者不兼容:

5.8.4 AuthenticationProvider 您可以通过将自定义 AuthenticationProvider 公开为 bean 来定义自定义身份验证。例如, 以下将自定义身份验证假设 SpringAuthenticationProvider 实现 AuthenticationProvider:

[注意] 仅当 AuthenticationManagerBuilder 没有 已填充

确实,如果我尝试使用以下方法检索 AuthenticationManager bean:

@Bean
public AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManagerBean();
}

那么configure() 方法甚至都不会被调用。

那么如何将我自己的自定义提供程序添加到默认提供程序列表中,并且仍然能够检索 AuthenticationManager?

【问题讨论】:

    标签: spring spring-security


    【解决方案1】:

    您可以直接覆盖 WebSecurityConfigurerAdapter.authenticationManagerBean() 方法并使用 @Bean 注释对其进行注释

     @Bean
     @Override
     public AuthenticationManager authenticationManagerBean() throws Exception {
         return super.authenticationManagerBean();
     }
    

    而且没有Spring Boot 5.0,最新发布的是Spring Boot 2.0。我相信你说的是 Spring Security 5.0。

    【讨论】:

    • 我知道答案就在眼前,但就是找不到。我不得不说,我有点惊讶,只是方法名称会产生如此大的差异。我原以为 Spring 会考虑到这种可能性(即:以不同的方式公开身份验证)
    猜你喜欢
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2016-01-08
    • 2017-09-17
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多