Restrict Ajax request caching in SpringSecurity
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.
- Create a class and extends it with HttpSessionRequestCache.
- 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 🙂