Spring阻止ajax调用成为身份验证的目标URL

时间:2015-12-18 22:21:36

标签: java ajax spring spring-mvc spring-security

我有一个有效的Spring / Java Web应用程序。在某些页面上,当我退出时,最后一个请求是AJAX调用。因此,当我重新登录时,Spring将我重定向到ajax调用,给我一个充满json的浏览器。我的登录成功处理程序扩展了SavedRequestAwareAuthenticationSuccessHandler

如何在成功登录时控制转发哪个网址?

2 个答案:

答案 0 :(得分:3)

最好的方法是首先防止缓存请求。如果您使用Spring Security的Java配置,它会自动忽略任何设置为“X-Requested-With:XMLHttpRequest”的请求。

您还可以使用RequestMatcher指定自己的<b:bean id="requestCache" class="org.springframework.security.web.savedrequest.HttpSessionRequestCache"> <b:property name="requestMatcher"> <b:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher"> <b:constructor-arg> <b:bean class="org.springframework.security.web.util.matcher.MediaTypeRequestMatcher"> <b:constructor-arg> <b:bean class="org.springframework.web.accept.HeaderContentNegotiationStrategy"/> </b:constructor-arg> <b:constructor-arg value="#{T(org.springframework.http.MediaType).APPLICATION_JSON}"/> </b:bean> </b:constructor-arg> <b:property name="useEquals" value="true"/> </b:bean> </b:property> </b:bean> <http ...> <!-- ... --> <request-cache ref="requestCache"/> </http> ,指定何时应保存请求。例如,您可以使用以下XML配置来忽略任何JSON请求:

arrItemNames

答案 1 :(得分:0)

我的解决方案受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
        }
    }
}

然后,在我的春季安全配置中:

<http>
    <request-cache ref="customRequestCache" />
</http>

使用此自定义请求缓存类时,不再存储ajax请求。

相关问题