如何在 Spring Security 中创建自定义身份验证过滤器?

Aug*_*mer 7 java spring-security spring-boot spring-filter

我正在尝试创建一个自定义 Spring Security 身份验证过滤器以实现自定义身份验证方案。我花了几个小时阅读 Spring Security,但我找到的所有指南都解释了如何配置基本设置;我正在尝试编写自定义设置,但无法找到有关如何执行此操作的文档。

举例来说,假设我的自定义身份验证方案如下:如果客户端在 http 请求中提供“foo_username”标头和“foo_password”标头(为了示例,两者均未加密),那么我的自定义过滤器需要构造一个 UsernamePasswordAuthenticationToken。当然,如果密码错误,那就是认证错误。如果任一标头丢失,则表示身份验证错误。如果两个标头都丢失,我想在不更改任何内容的情况下委托过滤器链。

理论上这看起来很简单,但我不知道如何在 Spring 中实现。我打算自己根据数据库检查密码吗?或者这是 UserDetailsPasswordService 的责任?我是否打算自己修改 SecurityContextHolder.getContext().authentication 字段?我应该将哪些职责委托给 AuthenticationManager?当各种方式认证失败时,会抛出哪些异常?我是否实现 Filter、OncePerRequestFilter 或 AbstractAuthenticationFilter?有没有关于如何执行这一切的文档???

诚然,这是如何使用 Spring security 创建自己的安全过滤器的重复?,但我不是他,他没有得到答案。

谢谢您的帮助!

Aug*_*mer 9

编辑:这不是最好的做事方式。它不遵循最佳实践。

正如其他人指出的那样,最好使用 Basic auth 或 OAuth2,两者都内置于 Spring 中。但如果你真的想实现自定义过滤器,你可以这样做。(如果我做错了,请纠正我。)但不要完全这样做。这不是一个非常安全的例子;这是一个简单的例子。

class CustomAuthenticationFilter(val authManager: AuthenticationManager) : OncePerRequestFilter() {

    override fun doFilterInternal(request: HttpServletRequest,
                                  response: HttpServletResponse,
                                  chain: FilterChain) {

        val username = request.getHeader("foo_username")
        val password = request.getHeader("foo_password")

        if(username==null && password==null){
            // not our responsibility. delegate down the chain. maybe a different filter will understand this request.
            chain.doFilter(request, response) 
            return
        }else if (username==null || password==null) {
            // user is clearly trying to authenticate against the CustomAuthenticationFilter, but has done something wrong.
            response.status = 401
            return
        }

        // construct one of Spring's auth tokens
        val authentication =  UsernamePasswordAuthenticationToken(username, password, ArrayList())
        // delegate checking the validity of that token to our authManager
        val userPassAuth = this.authManager.authenticate(authRequest)
        // store completed authentication in security context
        SecurityContextHolder.getContext().authentication = userPassAuth
        // continue down the chain.
        chain.doFilter(request, response)
    }
}
Run Code Online (Sandbox Code Playgroud)

创建身份验证过滤器后,不要忘记将其添加到 HttpSecurity 配置中,如下所示:

override fun configure(http: HttpSecurity?) {
    http!!.addFilterBefore(CustomAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter::class.java)
}
Run Code Online (Sandbox Code Playgroud)