当我们使用自定义过滤器时,我们需要注入类型为AuthenticationManager
的bean。
据我所知,如果我们使用默认过滤器,那么Spring将自动提供Authentication Manager。这使我得出结论,在Spring上下文中已经有一个AuthenticationManager
bean(根据我的理解)。
但问题是我的假设是不正确的。我必须创建并注入一个AuthenticationManager
bean到过滤器。
我的假设有什么问题?为什么我们需要在bean已经存在的情况下对其进行装箱?
Spring使用AuthenticationManager
查找适当的身份验证提供者,但默认情况下没有将AuthenticationManager
注册为bean。参见HttpSecurityConfiguration
类源代码
@Bean(HTTPSECURITY_BEAN_NAME)
@Scope("prototype")
HttpSecurity httpSecurity() throws Exception {
WebSecurityConfigurerAdapter.LazyPasswordEncoder passwordEncoder = new WebSecurityConfigurerAdapter.LazyPasswordEncoder(
this.context);
AuthenticationManagerBuilder authenticationBuilder = new WebSecurityConfigurerAdapter.DefaultPasswordEncoderAuthenticationManagerBuilder(
this.objectPostProcessor, passwordEncoder);
authenticationBuilder.parentAuthenticationManager(authenticationManager());
HttpSecurity http = new HttpSecurity(this.objectPostProcessor, authenticationBuilder, createSharedObjects());
// @formatter:off
http
.csrf(withDefaults())
.addFilter(new WebAsyncManagerIntegrationFilter())
.exceptionHandling(withDefaults())
.headers(withDefaults())
.sessionManagement(withDefaults())
.securityContext(withDefaults())
.requestCache(withDefaults())
.anonymous(withDefaults())
.servletApi(withDefaults())
.apply(new DefaultLoginPageConfigurer<>());
http.logout(withDefaults());
// @formatter:on
return http;
}
private AuthenticationManager authenticationManager() throws Exception {
return (this.authenticationManager != null) ? this.authenticationManager
: this.authenticationConfiguration.getAuthenticationManager();
}
在HttpSecurity
中注册了一个身份验证管理器构建器。稍后在HttpSecurity
类中,它将使用此构建器构建身份验证管理器并将其注册到共享对象中[参见HttpSecurity
中的beforeConfigure()
方法]。
@Override
protected void beforeConfigure() throws Exception {
setSharedObject(AuthenticationManager.class, getAuthenticationRegistry().build());
}
,当它需要身份验证时,管理器使用HttpSecurity
来获取,如下所示:
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);