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

时间:2013-08-08 21:13:52

标签: java spring spring-mvc spring-security

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

  1. 为Google Analytics设置跟踪事件代码,以便在前端使用
  2. 更新用户在数据库中的首选语言环境
  3. 在用户成功通过身份验证后,这些操作可能是您想要挂钩的任何操作。重要的是,与常规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);
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

在仔细查看AbstractAuthenticationProcessingFilter的源代码以及调用AuthenticationSuccessHandler.onAuthenticationSuccess(...)的所有其他地方之后,我认为没有任何可能使用Spring Security进行此操作。

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

相关问题