Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate between logout and session expired?

Case 1: Log out : Once we log out, if one tries to access previous, it must automatically redirect to login.jsp

Case 2: Session expired : If session expires when user is still logged in, it must try to automatically redirect to sessionExpired.jsp when previous page is accessed.

How to differentiate ? I am currently invalidating session when logging out.

like image 897
Prabhat Avatar asked Jul 22 '10 06:07

Prabhat


2 Answers

On login, set a cookie with a long expiry (> 24 hours). Remove this cookie at logout time by setting the maxage to 0.

You can have check for any non-logged in user (i.e. invalid session id). If the cookie does not exist, redirect him to login.jsp

If the cookie exists, it means his session expired so redirect him to session-expired.jsp

like image 87
JoseK Avatar answered Sep 21 '22 23:09

JoseK


You can test expired sessions by checking if HttpServletRequest#getRequestedSessionId() doesn't return null (which means that the client has sent a session cookie and thus assumes that the session is still valid) and HttpServletRequest#isRequestedSessionIdValid() returns false (which means that the session has been expired at the server side).

In a nut:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);

    if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
        response.sendRedirect(request.getContextPath() + "/sessionexpired.jsp");
    } else if (session == null || session.getAttribute("user") == null) {
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    } else {
        chain.doFilter(request, response);
    }
}

No need to hassle with extra cookies. Map this Filter on an url-pattern covering the protected pages (and thus excluding the sessionexpired and login pages!).

Don't forget to disable page caching by the browser on the protected pages, otherwise the webbrowser will load them from the cache when you're going back in the browser history, instead of sending a new request to the server. You can achieve this by doing the following in the same filter, before Chain#doFilter() call.

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
like image 28
BalusC Avatar answered Sep 18 '22 23:09

BalusC