jlars62 jlars62 - 1 year ago 123
Ajax Question

Spring prevent ajax call from being target url on authentication

I have a working Spring/Java web application. On some pages, when I log out, the last request to be made is an AJAX call. So, when I log back in, Spring redirects me to the ajax call giving me a browser full of json. My login success handler extends the


How can I control which url's get forwarded to on a successful login?

Answer Source

The best approach is to prevent the request from being cached in the first place. If you use Spring Security's Java Configuration it automatically ignores any request with "X-Requested-With: XMLHttpRequest" set.

You can also specify your own HttpSessionRequestCache with a RequestMatcher on it that specifies when a request should be saved. For example, you could use the following XML configuration to ignore any JSON requests:

<b:bean id="requestCache" 
  <b:property name="requestMatcher">
    <b:bean class="org.springframework.security.web.util.matcher.NegatedRequestMatcher">
        <b:bean class="org.springframework.security.web.util.matcher.MediaTypeRequestMatcher">
            <b:bean class="org.springframework.web.accept.HeaderContentNegotiationStrategy"/>
          <b:constructor-arg value="#{T(org.springframework.http.MediaType).APPLICATION_JSON}"/>
      <b:property name="useEquals" value="true"/>

<http ...>
    <!-- ... -->
    <request-cache ref="requestCache"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download