Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect user to login screen, If an ajax call is received after session timeout

I have a single page application, written using Jquery, java is used at the back-end.

After session timeout, If user do some activity which triggers Ajax call, then user should be redirected to login screen.
If It would have been an another page request, then following solution might have worked, but as it is Ajax call, redirection just give another response to success function.

I Tried

  1. In main Filter

    HttpSession session = request.getSession(false);
    if(session != null && !session.isNew()) {
        chain.doFilter(request, response);
    }else {
        response.sendRedirect("/login.jsp");
    }
    
  2. Refreshing the tab by sending below header on ajax call, from inside main filter

    httpResponse.setHeader("Refresh", "0; URL=" + targetUrl);
    
like image 986
sanjiv saini Avatar asked Jan 04 '23 10:01

sanjiv saini


2 Answers

server side: Add a filter, which will be processed for every single request, inside that filter's doFilter method add following code:

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;

HttpSession session = httpRequest.getSession(false);// don't create if it doesn't exist
if(session == null || session.isNew()) {
    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // status code is 401
}else{
    // pass the request along the filter chain
    chain.doFilter(request, response);
}

client side: configure ajax such that when it receives any response with status code 401, it reloads the tab or change the window.location. This is how it can be done using jquery:

$(window).load(function(){
    $.ajaxSetup({
        statusCode: {
            401: function(){
                    location.reload(); // or window.location="http://www.example.com"
                }
        }
    });
});

for me reloading was enough, to take the user to login screen

like image 183
sanjiv saini Avatar answered Jan 06 '23 02:01

sanjiv saini


One way you can do it is by

  1. having a common code for doing your ajax call
  2. Calling the backend from there
  3. Have logic setup

    if(response.status==403 || 404 or any code){ window.location = "http://your.login.page"; }

like image 33
vivek jha Avatar answered Jan 06 '23 03:01

vivek jha