當我們使用自定義過濾器時,我們需要注入一個 AuthenticationManager 的 bean。
據我所知,如果我們使用默認過濾器,那么 spring 會自動提供身份驗證管理器。這讓我得出結論,spring 背景關系中已經有一個 AuthenticationManager bean(根據我的理解)。
但問題是我的假設不正確。我必須將 AuthenticationManager 的 bean 打包并注入過濾器。
你能解釋一下我的假設有什么問題嗎?為什么我們需要在 bean 已經存在的情況下將其打包?
提前致謝。
uj5u.com熱心網友回復:
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類它將使用此構建構建一個認證管理器和在共享物件[見方法注冊它beforeConfigure()在HttpSecurity。
@Override
protected void beforeConfigure() throws Exception {
setSharedObject(AuthenticationManager.class, getAuthenticationRegistry().build());
}
每當它需要身份驗證管理器HttpSecurity來獲取時,如下所示:
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/335979.html
上一篇:Thymeaf計算出的URL值
