How to handle expired session using spring-securit

2019-01-31 02:06发布

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.

7条回答
唯我独甜
2楼-- · 2019-01-31 02:35

So there are 2 problems here. 1) Spring security is working, but the response is coming back to the browser in an ajax call. 2) Spring security keeps track of the originally requested page so that it can redirect you to it AFTER you log in (unless you specify that you always want to use a certain page after logging in). In this case, the request was an Ajax string, so you will be re-directed to that string and that is what you will see in the browser.

A simple solution is to detect the Ajax error, and if the request sent back is specific to your login page (Spring will send back the login page html, it will be the 'responseText' property of the request) detect it. Then just reload your current page, which will remove the user from the context of the Ajax call. Spring will then automatically send them to the login page. (I am using the default j_username, which is a string value that is unique to my login page).

$(document).ajaxError( function(event, request, settings, exception) {
    if(String.prototype.indexOf.call(request.responseText, "j_username") != -1) {
        window.location.reload(document.URL);
    }
});
查看更多
登录 后发表回答