Java Spring防止ajax调用成为身份验证的目标url
我有一个工作的Spring/JavaWeb应用程序。在某些页面上,当我注销时,最后一个请求是AJAX调用。因此,当我重新登录时,Spring会将我重定向到ajax调用,给我一个充满json的浏览器。我的登录成功处理程序扩展了Java Spring防止ajax调用成为身份验证的目标url,java,ajax,spring,spring-mvc,spring-security,Java,Ajax,Spring,Spring Mvc,Spring Security,我有一个工作的Spring/JavaWeb应用程序。在某些页面上,当我注销时,最后一个请求是AJAX调用。因此,当我重新登录时,Spring会将我重定向到ajax调用,给我一个充满json的浏览器。我的登录成功处理程序扩展了SavedRequestAwareAuthenticationSuccessHandler 如何控制成功登录时转发到哪个url?最好的方法是首先防止缓存请求。如果使用SpringSecurity的Java配置,它会自动忽略设置了“X-Requested-with:XMLHtt
SavedRequestAwareAuthenticationSuccessHandler
如何控制成功登录时转发到哪个url?最好的方法是首先防止缓存请求。如果使用SpringSecurity的Java配置,它会自动忽略设置了“X-Requested-with:XMLHttpRequest”的任何请求 您还可以指定自己的
HttpSessionRequestCache
,其上有一个RequestMatcher
,指定保存请求的时间。例如,您可以使用以下XML配置忽略任何JSON请求:
我的解决方案灵感来自Rob Winch的答案。不过,在我的场景中,Spring保存了设置了
X-request-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请求将不再被存储。发布一些代码,看看您是如何做到这一点的。我终于开始修复此问题。谢谢你的回答!这对我有用,谢谢!回答中的一个小错误是,
usequals
属性位于MediaTypeRequestMatcher
中,而不是NegatedRequestMatcher
。