Restrict Ajax request caching in SpringSecurity

11 / Feb / 2016 by Jitendra Singh 0 comments

Spring Security has a nice feature of request caching. When user try to access secured resource without logging in into the system, spring security caches that request and redirect the user to the login page. After successful authentication it redirects user to that cached request. This works for both Ajax and non-ajax requests. To restrict request caching for Ajax request in Grails App, we just need to follow some steps.

  1. Create a class and extends it with HttpSessionRequestCache.
  2. Override its saveRequest() method

[java]

class CustomHttpSessionRequestCache extends HttpSessionRequestCache {
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
if(!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
super.saveReqeust(request, response);
}
}
}

[/java]

Now register it as spring bean with name requestCache in your resources.groovy file

[java]

requestCache(ApplicationHttpSessionRequestCache) {
portResolver = ref(‘portResolver’)
createSessionAllowed = conf.requestCache.createSession // true
requestMatcher = ref(‘requestMatcher’)
}

[/java]

 

Thats it 🙂

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *