'automatically redirect to login page after session timeout - JSP, Spring

I can redirect a user to home page upon session logout.. this was very simple. However, if an user had logged into the app and had the page open, even on session time out, he is able to perform all the functions(this is bad).

The redirect does not happen until the page is refreshed, or submitted to the server... there are some update functions that could be done by the user even if he is not currently logged in... I have done a lot of research but unable to fix this solution. I also found this thread but it seems to have no proper answer:

Spring Security 3.1 - Automatically redirect to login page when session-timeout occurs

For example, most of the banking sites log you out after a time out.. they do not wait until you come back and then submit a request before you are redirected to home page.



Solution 1:[1]

HTTP is stateless. To achieve some form of state the server can maintain a session for each user by giving them a session id on their first request. The user would have to resend that session id on each future request to identify that the other requests happen within the same session.

Because the session is maintained by the server, there is no way to notify the client that the session has timed out.

Instead, if the user makes a new request when the session is timed out, their session ID is no longer good and therefore you can take a particular action like redirect them to login page.

Solution 2:[2]

Assuming nothing works out. You may want to consider below mentioned approches:

Approach 1: Create a cookie on browser and have encrypted timestamp in it that will contain last visited/request timestamp from browser, for each request first get get this cookie value and compare with the pre-defined session out time, if session-out time reached then redirect user to error page else serve the request. On logout delete the cookie.

Why encrypted value for timestamp: if somehow user gets to know about cookie used for session timeout then (s)he can change this value in browser and keep on sending this request.

Approach 2: You can also achieve this by making an entry in your database for every logged-in user and updating timestamp in this database for each request. For each incoming request get this timestamp from database and compare it with pre-defined value for timeout and handle accordingly. On logout delete the entry.

In both the approaches explicitly perform response.redirect("errorPageUrl");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sotirios Delimanolis
Solution 2 Rupesh