使用 AuthenticationManagerBuilder 添加自定义提供程序时如何获取 AuthenticationManager?

Eri*_* B. 3 spring spring-security

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

前任:

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

在哪里customAuthenticationProvider实现AuthenticationProvider

Spring docs 中,似乎指定两者不兼容:

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

[注意] 仅在未填充 AuthenticationManagerBuilder 时使用

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

@Bean
public AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManagerBean();
}
Run Code Online (Sandbox Code Playgroud)

那么该configure()方法甚至永远不会被调用。

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

sha*_*zin 5

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

 @Bean
 @Override
 public AuthenticationManager authenticationManagerBean() throws Exception {
     return super.authenticationManagerBean();
 }
Run Code Online (Sandbox Code Playgroud)

并且没有 Spring Boot 5.0,最新版本是 Spring Boot 2.0。我相信你在谈论 Spring Security 5.0。