jlars62 jlars62 - 13 days ago 5
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

SavedRequestAwareAuthenticationSuccessHandler
.

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

Answer

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" 
        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>
Comments