I'm using spring-security and jQuery in my application. Main page uses loading content dynamically into tabs via Ajax. And all is ok, however sometimes I've got the login page inside my tab and if I type credentials I will be redirected to the content page without tabs.
So I'd like to handle this situation. I know some of the people use ajax authentication, but I'm not sure it's suitable for me because it looks quite complicated for me and my application doesn't allow any access without log into before. I would like to just write a global handler for all ajax responses that will do window.location.reload()
if we need to authenticate. I think in this case it's better to get 401
error instead of standard login form because it's easier to handle.
So,
1) Is it possible to write global error handler for all jQuery ajax requests?
2) How can I customize behavior of spring-security to send 401 error for ajax requests but for regular requests to show standard login page as usual?
3) May be you have more graceful solution? Please share it.
Thanks.
I just came up with a solution to this problem, but haven't tested it thoroughly. I am also using spring, spring security, and jQuery. First, from my login's controller, I set the status code to 401:
In their onload() methods, all of my pages call a function in my global javascript file:
}
At this point, you can handle the 401 error any way you like. In one project, I have handled jQuery authentication by putting a jQuery dialog around an iframe containing a login form.
Here's how I typically do it. On every AJAX call, check the result before using it.
And then the
HasErrors()
function looks like this, and can be shared on all pages.When a timeout occurs, user is redirected to login page after any ajax action is triggered while session already cleared
security context :
Login listener :
}
Here's an approach that I think is quite simple. It's a combination of approaches that I've observed on this site. I wrote a blog post about it: http://yoyar.com/blog/2012/06/dealing-with-the-spring-security-ajax-session-timeout-problem/
The basic idea is to use an api url prefix (i.e. /api/secured) as suggested above along with an authentication entry point. It's simple and works.
Here's the authentication entry point:
And here's what goes in your spring context xml:
I used the following solution.
In spring security defined invalid session url
For that page added following controller
And for ajax used ajaxSetup to handle all ajax requests:
Take a look at http://forum.springsource.org/showthread.php?t=95881, I think the proposed solution is much clearer than other answers here: