Spring Security的配置機(jī)制早就變了,你發(fā)現(xiàn)了嗎?
以前胖哥說(shuō)過(guò)SecurityConfigurerAdapter會(huì)在即將發(fā)布的5.7版本作廢,從Spring Security 5.4版本開(kāi)始會(huì)提供一個(gè)原型范圍的HttpSecurity來(lái)幫助我們構(gòu)建過(guò)濾器鏈SecurityFilterChain:
@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;
}
這里會(huì)構(gòu)建基于原型的HttpSecurityBean,并且初始化了一些默認(rèn)配置供我們來(lái)使用。涉及Spring Security的日常開(kāi)發(fā)都是圍繞這個(gè)類進(jìn)行的,所以這個(gè)類是學(xué)習(xí)Spring Security的重中之重。
基于原型(prototype)的Spring Bean的一個(gè)典型應(yīng)用場(chǎng)景。
基本配置
日常我們使用的一些配置項(xiàng)如下:
方法 說(shuō)明
requestMatchers() 為SecurityFilterChain提供URL攔截策略,具體還提供了antMatcher和mvcMathcer
openidLogin() 用于基于 OpenId 的驗(yàn)證
headers() 將安全標(biāo)頭添加到響應(yīng),比如說(shuō)簡(jiǎn)單的 XSS 保護(hù)
cors() 配置跨域資源共享( CORS )
sessionManagement() 配置會(huì)話管理
portMapper() 配置一個(gè)PortMapper(HttpSecurity#(getSharedObject(class))),其他提供SecurityConfigurer的對(duì)象使用 PortMapper 從 HTTP 重定向到 HTTPS 或者從 HTTPS 重定向到 HTTP。默認(rèn)情況下,Spring Security使用一個(gè)PortMapperImpl映射 HTTP 端口8080到 HTTPS 端口8443,HTTP 端口80到 HTTPS 端口443
jee() 配置基于容器的預(yù)認(rèn)證。在這種情況下,認(rèn)證由Servlet容器管理
x509() 配置基于x509的預(yù)認(rèn)證
rememberMe 配置“記住我”的驗(yàn)證
authorizeRequests() 基于使用HttpServletRequest限制訪問(wèn)
requestCache() 配置請(qǐng)求緩存
exceptionHandling() 配置錯(cuò)誤處理
securityContext() 在HttpServletRequests之間的SecurityContextHolder上設(shè)置SecurityContext的管理。當(dāng)使用WebSecurityConfigurerAdapter時(shí),這將自動(dòng)應(yīng)用
servletApi() 將HttpServletRequest方法與在其上找到的值集成到SecurityContext中。當(dāng)使用WebSecurityConfigurerAdapter時(shí),這將自動(dòng)應(yīng)用
csrf() 添加 CSRF 支持,使用WebSecurityConfigurerAdapter時(shí),默認(rèn)啟用
logout() 添加退出登錄支持。當(dāng)使用WebSecurityConfigurerAdapter時(shí),這將自動(dòng)應(yīng)用。默認(rèn)情況是,訪問(wèn)URL”/ logout”,使HTTP Session無(wú)效來(lái)清除用戶,清除已配置的任何#rememberMe()身份驗(yàn)證,清除SecurityContextHolder,然后重定向到/login?success
anonymous() 配置匿名用戶的表示方法。當(dāng)與WebSecurityConfigurerAdapter結(jié)合使用時(shí),這將自動(dòng)應(yīng)用。默認(rèn)情況下,匿名用戶將使用org.springframework.security.authentication.AnonymousAuthenticationToken表示,并包含角色 ROLE_ANONYMOUS
authenticationManager() 配置AuthenticationManager
authenticationProvider() 添加AuthenticationProvider
formLogin() 指定支持基于表單的身份驗(yàn)證。如果未指定FormLoginConfigurer#loginPage(String),則將生成默認(rèn)登錄頁(yè)面
oauth2Login() 根據(jù)外部OAuth 2.0或OpenID Connect 1.0提供程序配置身份驗(yàn)證
oauth2Client() OAuth2.0 客戶端相關(guān)的配置
oauth2ResourceServer() OAuth2.0資源服務(wù)器相關(guān)的配置
requiresChannel() 配置通道安全。為了使該配置有用,必須提供至少一個(gè)到所需信道的映射
httpBasic() 配置 Http Basic 驗(yàn)證
addFilter() 添加一個(gè)已經(jīng)在內(nèi)置過(guò)濾器注冊(cè)表注冊(cè)過(guò)的過(guò)濾器實(shí)例或者子類
addFilterBefore() 在指定的Filter類之前添加過(guò)濾器
addFilterAt() 在指定的Filter類的位置添加過(guò)濾器
addFilterAfter() 在指定的Filter類的之后添加過(guò)濾器
and() 連接以上策略的連接器,用來(lái)組合安全策略。實(shí)際上就是”而且”的意思
高級(jí)玩法
新手建議先把上面的基本玩法有選擇的弄明白,然后有精力的話去研究下HttpSecurity的高級(jí)玩法。
apply
這個(gè)方法用來(lái)把其它的一些配置合并到當(dāng)前的配置中去,形成插件化,支持SecurityConfigurerAdapter或者SecurityConfigurer的實(shí)現(xiàn)。其實(shí)內(nèi)置的一些配置都是以這種形式集成到HttpSecurity中去的。例如文章開(kāi)頭的配置中有默認(rèn)登錄頁(yè)面相關(guān)的配置:
httpSecurity.apply(new DefaultLoginPageConfigurer<>());
胖哥就利用這個(gè)搞了一個(gè)支持小程序登錄和驗(yàn)證碼登錄的擴(kuò)展 spring-security-login-extension。
objectPostProcessor配置一個(gè)自定義ObjectPostProcessor。ObjectPostProcessor可以改變某些配置內(nèi)部的機(jī)制,這些配置往往不直接對(duì)外提供操作接口。
獲取、移除配置類
getConfigurer用來(lái)獲取已經(jīng)apply的配置類;getConfigurers用來(lái)獲取已經(jīng)apply某個(gè)類型的所有配置類。這個(gè)現(xiàn)在是我最喜歡的自定義的方式。
配置、獲取SharedObjectShared
Object是在配置中進(jìn)行共享的一些對(duì)象,HttpSecurity共享了一些非常有用的對(duì)象可以供各個(gè)配置之間共享,比如AuthenticationManager。相關(guān)的方法有setSharedObject、getSharedObject、getSharedObjects。
獲取SecurityFilterChainHttpSecurity也提供了構(gòu)建目標(biāo)對(duì)象SecurityFilterChain的實(shí)例的方法。你可以通過(guò)build()來(lái)對(duì)配置進(jìn)行初次構(gòu)建;也可以通過(guò)getObject()來(lái)獲取已經(jīng)構(gòu)建的實(shí)例;甚至你可以使用getOrBuild()來(lái)進(jìn)行直接獲取實(shí)例或者構(gòu)建實(shí)例。
所以新的配置都是這樣的:
@Bean
SecurityFilterChain securityFilterChain (HttpSecurity http) {
http.cors();
return http.build();
}
記住每一個(gè)HttpSecurity只能被構(gòu)建成功一次。
這一篇非常重要本篇東西非常重要,不是馬上就能掌握的,需要有些耐心,需要在使用和學(xué)習(xí)中總結(jié)和發(fā)現(xiàn)。