Automatically logout when user is idle for sometime

Automatically logout when user is idle for sometime :


When working with corporate application, many a times we are given requirement that when user is logged in to the application and have left the application idle for certain amount of time, he/she should be automatically logged out to avoid leaking of application specific information or misuse of the application.This is very frequently asked feature in banking, finance and other information sensitive web application.

In this Post, we shall learn very easy way to achieve automatic logout when user is idle for sometime in the application.

To demonstrate this, I have created a very simple web page. In real time scenario, we can enhance this or add/remove whatever is necessary.

Creating a sample automatic logout notification page

Below is the <script> code. This should ideally be kept inside the _Layout/Master/Template page so that this code executes in almost all pages of the application.
In this code, we are first referencing to the jQuery page.

On load of the page, we are attaching click and keypress event on the "body" element of the page and when these event fires, we are calling ResetThisSession() function.
Next, we have declared a variable named timeInSecondsAfterSessionOut that holds the value defined in number of seconds the user should be automatically logged out.

Next, we have declared a variable named secondTick, treat this as second needle of the watch that will be incremented after every second.

After that we have declared ResetThisSession() function that simply sets the secondTick value to 0.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script>
        $(function () {
            $("body").on('click keypress', function () {
                ResetThisSession();
            });
        });

  var timeInSecondsAfterSessionOut = 30;
        var secondTick = 0;

        function ResetThisSession() {
            secondTick = 0;
        }

        function StartThisSessionTimer() {
            secondTick++;
            var timeLeft = ((timeInSecondsAfterSessionOut - secondTick) / 60).toFixed(0);
        timeLeft = timeInSecondsAfterSessionOut - secondTick;

            $("#spanTimeLeft").html(timeLeft);

            if (secondTick > timeInSecondsAfterSessionOut) {
                clearTimeout(tick);
                window.location = "/Logout.aspx";
                return;
            }
            tick = setTimeout("StartThisSessionTimer()", 1000);
        }

        StartThisSessionTimer();
</script>


JQuery related Posts:




Comments

Popular posts from this blog