How to get login page in the main window in Spring after a jQuery Ajax call

294 Views Asked by At

I have an AJAX based web application written in SPRING and jQuery. For authentication I use Spring security.I start the application with the individual login page (not integrated into the applcation window) and I want to end up like that after the session time out. However, when the session times out during an AJAX call a Login page (served by the Spring security) is inserted in the "div" where the result of the AJAX call was supposed to come. Therefore, I end up with the situation when I have the login page in the sub-part of the application window,instead of one singe login page. I am searching for some solution on the server side,not in jQuery, if possible. My initial idea was doing something like this:

public class AjaxAwareLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
    if (request.getHeader("X-Requested-With").equals("XMLHttpRequest")) {
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(request, response, "/j_spring_security_logout");
    } else {
        super.commence(request, response, authException);
    }
}

The idea was to force LoginUrlAuthenticationEntryPoint to make a logout call, hoping the whole page would be replaced be the login form beeing returned. This obviously does not work. What should be the correct way to handle this issue?Thank you!

EDITED - ONE SOLUTON: Ok, So I finally haven't manage without the client side code as kryger recommended. What finally worked for me was

1) at server side implementing custom LoginUrlAuthenticationEntryPoint:

public class AjaxAwareLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
    if (request.getHeader("X-Requested-With").equals("XMLHttpRequest")) {
        setUseForward(true);
        response.setHeader("Reload-to-loginpage", "yes");
        super.commence(request, response, authException);
    } else {
        super.commence(request, response, authException);
    }
}

note using

setUseForward(true);

to get the request forwarded with the header.

2) on the client side simply

$(document).ajaxSuccess(function(event, request, settings) {
                if (request.getResponseHeader('Reload-to-loginpage') === 'yes') {
                    window.location.replace('/YOURWEBSITE');
                }
            });

and possibly the same for .ajaxError() unless you handle errors in some special way. Please,let me know if I can improve the code!

0

There are 0 best solutions below