Redirect after AJAX request / Control authentication failure after AJAX request

Last two days I’ve been dealing with a problem I’ve had with some of the projects I work on. For our Java web apps we use an authentication/authorization filter that redirects to a login page after an authentication/authorization error. This error can be a login error, a session timeout or other things.

Redirect calls are managed by browsers without problems, they do the request for the new location and the login page is presented to you. But if your app does AJAX requests, as every app nowadays does, you’ll get into troubles, the browser won’t do any redirection, so your app will stay in the same page as before the request, and probably the user will be annoyed because your app doesn’t respond or does strange things. The login page won’t be shown until the user clicks on a non AJAX component (menu, link or so), or does a refresh.

Usually the authentication filter does a sendRedirect to the login page when there is an authentication problem:

response.sendRedirect(response.encodeRedirectURL(url));
response.flushBuffer();

So after some research I found that doing a manual redirect should solve the problem with AJAX calls. Really I didn’t know why doing this would solve the problem, but I tried it:

...
if (isAjax(request)) {
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='UTF-8'?>");
    sb.append("<partial-response><redirect url=\"").append(response.encodeRedirectURL(url.toString())).append("\"/></partial-response>");
    response.getWriter().print(sb.toString());
    response.flushBuffer();
}

private boolean isAjax(HttpServletRequest request) {
    return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}

Even I tried to send a redirect HTTP’s 302 code or adding a Location header… without any succeed:

if (isAjax(request)) {
    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", response.encodeRedirectURL(url.toString()));
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='UTF-8'?>");
    sb.append("<partial-response><redirect url=\"").append(response.encodeRedirectURL(url.toString())).append("\"/></partial-response>");
    response.getWriter().print(sb.toString());
    response.flushBuffer();
}

private boolean isAjax(HttpServletRequest request) {
    return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}

Then I tried to solve it from the other side, thus is, the client. I didn’t like it, because it is easier to distribute a JAR file with the authentication filter solution than telling people what they must do in every app they are developing. Although we have projects with JSP/JQuery or Seam 2, the last apps we’re working on use Primefaces, so I tried to find a solution related to this framework. First I tried to catch onComplete events within ajaxStatus Primefaces tag, but this component doesn’t pass the XMLHttpRequest argument to the callbacks, also I tried to bind a callback to onComplete events at body or document level, but any result was good.

Finally I went for a more drastic and I think the most secure solution: Setting up every AJAX call that could be made within our apps to do what I want when an authentication error raised. For this, JQuery has a solution, the $.ajaxSetup function. With it you can define at a global level how AJAX calls behave, and when I say at a global level I mean that every AJAX call from your code, or from whatever library or framework you are using will do what you define with this function. So first of all I changed the HTTP code the filter was sending, instead of a 302 now it sends a 401 (unauthorized), then I defined the behaviour of AJAX calls after receiving this code:

First the changes in the Java code:

if (isAjax(request)) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.setHeader("Location", response.encodeRedirectURL(url.toString()));
    response.flushBuffer();
}
private boolean isAjax(HttpServletRequest request) {
    return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}

Now the Javascript code:

function requestUnauthorized(xhr) {
    window.location.href = xhr.getResponseHeader("Location");
}
 
(function($) {
    $.ajaxSetup({
        statusCode: {
            401: requestUnauthorized,
        }
    });
})(window.jQuery);

The syntax…

(function($){.....})(window.jQuery) 

…means that you’re defining an anonymous function with an parameter called $, that will be self-executed with window.jQuery as value. It’s better to use window.jQuery because some libraries or frameworks rename jQuery to $, $$ or whatever they want.

And that’s all, you have to put the Javascript code somewhere that is visible for the whole app.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s