Spring防止Ajax调用成为身份验证的目标URL
问题内容:
我有一个运行中的Spring / Java
Web应用程序。在某些页面上,当我注销时,要发出的最后一个请求是AJAX调用。因此,当我重新登录时,Spring将我重定向到ajax调用,这给了我一个充满json的浏览器。我的登录成功处理程序扩展了SavedRequestAwareAuthenticationSuccessHandler
。
如何控制成功登录后转发到哪个网址?
问题答案:
我的解决方案受Rob Winch的回答启发。尽管在我的场景中,Spring 正在 保存已X-Requested-With: XMLHttpRequest
设置的请求。这些是我不得不忽略的要求。
我创建了一个类作为自定义RequestCache
类。
@Service("customRequestCache")
public class CustomRequestCache extends HttpSessionRequestCache { //this class (bean) is used by spring security
@Override
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
if (!"XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
//request is not ajax, we can store it
super.saveRequest(request, response);
} else {
//do nothing, add some logs if you want
}
}
}
然后,在我的spring安全配置中:
<http>
<request-cache ref="customRequestCache" />
</http>
使用此自定义请求缓存类后,不再存储ajax请求。