Spring Security自定义认证AuthenticationProcessingFilter

前言

采用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
在这里插入图片描述在这里插入图片描述

发布了28 篇原创文章 · 获赞 2 · 访问量 7344

猜你喜欢

转载自blog.csdn.net/leyuuu/article/details/104038429