最简单的方法来调用多个AuthenticationSuccessHandlers?

Ste*_*e K 5 java spring spring-mvc spring-security

我有一个使用Spring 3.1的java webapp.My Spring安全上下文定义了多个身份验证过滤器,每个过滤器对应不同的身份验证路径(例如用户名/密码与单点登录).每个auth过滤器定义自己的AuthenticationSuccessHandler.现在,我想在成功进行身份验证时注入2个额外的操作,它们应该适用于所有身份验证类型:

  1. 设置Google Analytics的跟踪事件代码,以便在前端使用
  2. 在我们的数据库中更新用户的首选语言环境

在用户成功通过身份验证后,这些操作可能是您想要挂钩的任何操作.重要的是,与常规AuthenticationSuccessHandler(每个身份验证路径不同)不同,它们不会转发或重定向请求.所以打电话给他们是很安全的.

有没有一种干净的方法来使用Spring Web/Security 3.1集成这些额外的身份验证成功"操作"?

我考虑实现一个ApplicationListener<AuthenticationSuccessEvent>,但我的事件需要访问请求,所有AuthenticationSuccessEvent提供的都是Authentication对象本身.

我找不到方法,所以我决定推出自己的代理:

public class AuthenticationSuccessHandlerProxy implements AuthenticationSuccessHandler {
    private List<AuthenticationSuccessHandler> authenticationSuccessHandlers;

    public AuthenticationSuccessHandlerProxy(List<AuthenticationSuccessHandler> successHandlers) {
        this.authenticationSuccessHandlers = successHandlers;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        for (AuthenticationSuccessHandler successHandler : this.authenticationSuccessHandlers) {
            successHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mak*_*das 0

在简要查看了 的源代码AbstractAuthenticationProcessingFilter和所有其他调用的地方之后AuthenticationSuccessHandler.onAuthenticationSuccess(...),我看不到任何使用 Spring Security 来做到这一点的可能性。

作为解决方法,您可以尝试将成功处理程序包装到某些 AspectJ 或 AOP 切入点中,然后将此切入点应用于AuthenticationSuccessHandler.onAuthenticationSuccess(...)执行。也许像这样您可以定位所有身份验证类型。