Spring prevent ajax call from destination URL during authentication

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

How can I control which URL will be redirected to a successful login?

+3
source share
2 answers

My decision is inspired by Rob Vinca's answer. Although, in my scenario, Spring was saving requests with the X-Requested-With: XMLHttpRequest setting. These were requests that I had to ignore.

I created a class that will be my regular RequestCache class.

 @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 } } } 

Then in my Spring Security Configuration:

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

When using this custom request cache class, ajax requests are no longer saved.

0
source

The best approach is to prevent a cache request first. If you use Spring Security Java Configuration, it will automatically ignore any request using the "X-Requested-With: XMLHttpRequest" set.

You can also specify your own HttpSessionRequestCache with RequestMatcher on it, which indicates when the request should be saved. For example, you can 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> 
+2
source

Source: https://habr.com/ru/post/1381786/


All Articles