我有一个使用 Spring 3.1 的 java webapp。我的 Spring 安全上下文定义了多个身份验证过滤器,每个过滤器对应一个不同的身份验证路径(例如,用户名/密码与单点登录)。每个身份验证过滤器都定义了自己的 AuthenticationSuccessHandler
.现在,我想注入(inject) 2 个附加操作以在成功验证后执行,它们应该适用于所有 验证类型:
- 为前端使用的 Google Analytics 设置跟踪事件代码
- 在我们的数据库中更新用户的首选语言环境
在用户成功通过身份验证后,这些可以是您想要 Hook 的任何操作。重要的一点是,与常规的 AuthenticationSuccessHandlers(每个身份验证路径不同)不同,它们不会转发或重定向请求。所以调用他们是安全的。
是否有一种干净的方法来使用 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);
}
}
}
最佳答案
在简单地查看了 AbstractAuthenticationProcessingFilter
的源代码和所有其他调用 AuthenticationSuccessHandler.onAuthenticationSuccess(...)
的地方后,我看不出有任何可能这样做使用 Spring Security。
作为解决方法,您可以尝试将成功处理程序包装到某些 AspectJ 或 AOP 切入点中,然后将此切入点应用于 AuthenticationSuccessHandler.onAuthenticationSuccess(...)
执行。也许像这样您可以针对所有身份验证类型。
关于java - 调用多个 AuthenticationSuccessHandler 的最干净的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18136250/