views:

140

answers:

1

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.

A: 

Here's how I typically do it. On every AJAX call, check the result before using it.

$.ajax({ type: 'GET',
    url: GetRootUrl() + '/services/dosomething.ashx',
    success: function (data) {
      if (HasErrors(data)) return;

      // process data returned...

    },
    error: function (xmlHttpRequest, textStatus) {
      ShowStatusFailed(xmlHttpRequest);
    }
  });

And then the HasErrors() function looks like this, and can be shared on all pages.

function HasErrors(data) {
  // check for redirect to login page
  if (data.search(/login\.aspx/i) != -1) {
    top.location.href = GetRootUrl() + '/login.aspx?lo=TimedOut';
    return true;
  }
  // check for IIS error page
  if (data.search(/Internal Server Error/) != -1) {
    ShowStatusFailed('Server Error.');
    return true;
  }
  // check for our custom error handling page
  if (data.search(/Error.aspx/) != -1) {
    ShowStatusFailed('An error occurred on the server. The Technical Support Team has been provided with the error details.');
    return true;
  }
  return false;
}
Glen Little