Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Session Timeout in Ajax Request in Spring MVC

Tags:

I can't see seem to find a good example/answer on how to send back some data from an ajax request when a session has timed out. It sends back the login page HTML and I want to either send json or a status code I can intercept.

like image 779
Mike Flynn Avatar asked Feb 10 '11 23:02

Mike Flynn


People also ask

Will Ajax call keep session alive?

Yes it's safe. As far as load, that's up to your hardware and how you write it, but it has no worse effect than users refreshing the page (arguably less considering the overhead of an AJAX call over a standard page load). You can adjust the timeout in the web.

What is spring session timeout?

If we don't specify the duration unit, Spring will assume it's seconds. In a nutshell, with this configuration, the session will expire after 15 minutes of inactivity. The session is considered invalid after this period of time.

What is default session timeout in spring boot?

After deploying the war file manually to tomcat, I realized that default session timeout value (30 min) was being used still.


1 Answers

The simplest way for doing this is using a filter on URLs of your AJAX requests.

In the example below I'm just sending HTTP 500 response code with a response body indicating the session timeout, but you can easily set the response code and body to what is more suitable for your case..

package com.myapp.security.authentication;  import org.springframework.web.filter.GenericFilterBean;  import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;  public class ExpiredSessionFilter extends GenericFilterBean {      static final String FILTER_APPLIED = "__spring_security_expired_session_filter_applied";      @Override     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {          HttpServletRequest request = (HttpServletRequest) req;         HttpServletResponse response = (HttpServletResponse) res;          if (request.getAttribute(FILTER_APPLIED) != null) {             chain.doFilter(request, response);             return;         }          request.setAttribute(FILTER_APPLIED, Boolean.TRUE);         if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {                            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "SESSION_TIMED_OUT");             return;         }          chain.doFilter(request, response);     } } 
like image 188
Boris Kirzner Avatar answered Sep 22 '22 17:09

Boris Kirzner