前言
採用Kotlin代碼
業務需要SSO登陸,所以要自己去寫一些SpringFilter 去判斷認證 獲取用戶信息 而不是默認實現
本文包含作者在理解Spring Security中遇到的困難
文筆粗糙,只爲讀者提供部分參考
如何判斷認證成功 如何判斷認證失敗
後話
關鍵在於AbstractAuthenticationProcessingFilter中的2個方法
successfulAuthentication
unsuccessfulAuthentication
那成功失敗的回調怎麼添加呢?
初始化的時候綁定2個回調函數
下面代碼是kotlin的 lambda簡化
class UserAccessFilter(authenticationManager: AuthenticationManager?) : AbstractAuthenticationProcessingFilter(AntPathRequestMatcher("/**", "GET")) {
init {
this.authenticationManager = authenticationManager
setAuthenticationFailureHandler{req,res,auth ->
res.sendRedirect("/signin")
}
setAuthenticationSuccessHandler{req,res,auth ->
println("Auth OK")
}
}
}
執行時機就是抽象類的這2個方法
有些頁面不想用上面的Filter進行認證呢?
override fun configure(http: HttpSecurity) {
http.authorizeRequests()
.antMatchers("/signin", "/sso", "/prometheus/**").anonymous()
.antMatchers("/**").authenticated()
}
//不知爲啥沒出效果
姑且配置了另外的配置方法解決了
override fun configure(web: WebSecurity) {
web.ignoring().antMatchers("/signin", "/sso", "/prometheus/**");
}
Filter已進行Token驗證但是到了WebExpressionVoter來投票了就變成了anonymousUser
最後發現是filter最後驗證完成後沒有調用父類方法successfulAuthentication
所以後面的Filter任然不知道用戶有無認證成功
override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
val httpRequest = request as HttpServletRequest
val httpResponse = response as HttpServletResponse
val authResult = attemptAuthentication(httpRequest,httpResponse)
successfulAuthentication(httpRequest,httpResponse,chain,authResult)
chain?.doFilter(request, response)
}
兩張圖來自https://blog.csdn.net/zhangchen2449/article/details/52623122