Automatically logout when user is idle for sometime

Sheonarayan
Posted by in jQuery category on for Advance level | Points: 250 | Views : 55408 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we shall learn how to automatically logout user when he/she is idle for certain amount of time in the application. To make it efficient and easy, we shall use jQuery to achieve this functionality however it can be done using plane JavaScript as well.


 Download source code for Automatically logout when user is idle for sometime

Recommendation
Read Dynamically append data to the grid in ASP.NET with jQuery before this article.

Introduction

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 article, 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; // change this to change session time out (in seconds).
        var secondTick = 0;

        function ResetThisSession() {
            secondTick = 0;
        }

        function StartThisSessionTimer() {
            secondTick++;
            var timeLeft = ((timeInSecondsAfterSessionOut - secondTick) / 60).toFixed(0); // in minutes
        timeLeft = timeInSecondsAfterSessionOut - secondTick; // override, we have 30 secs only 

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

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

        StartThisSessionTimer();
</script>
In StartThisSessionTimer() function we have incremented the value of secondTick and calculating time left by decreasing this by timeInSecondsAfterSessionOut, we can write this value either in minutes or seconds. In case, this value is coming large in number its good idea to divide by 60 to get in minutes (same as written in above code snippet). However, I have overridden this in above code snippet as in this demo, my timeout value is only  30 seconds.



The timeLeft is then being written in the <span> element to let user know that he/she has this much time before he/she will automatically be logged out if he/she doesn't perform any activity like clicking on the page or writing something.

Next, we are checking if secondTick is greater than timeInSecondsAfterSessionOut then we are calling clearTimeout javascript function that stops the timer and redirect the user to "/Logout.aspx" page else this function executes again after 1 seconds (this is recursive function) because of setTimeout javascript function.

At last we have called StartThisSessionTimer() function so that as soon as page loads, the time starts.

The HTML page doesn't have any significance here however just for clarity purpose I have given below code snippet of the demo page.

<body>
    <form id="form1" runat="server">
    <div>
        <table style="width:100%;">
            <tr>
                <td><h2>Welcome to my webiste</h2></td>
                <td style="text-align:right;"><span id="spanTimeLeft"></span> seconds left</td>
            </tr>
        </table>
        <hr />
        Content goes here. Content goes here. Content goes here. Content goes here. 
        Content goes here. Content goes here. Content goes here. Content goes here. 
        Content goes here. Content goes here. 
    </div>
    </form>
</body>
So you can see that applying auto logout functionality is very easy to implement in any web page, it doesn't need any server side code, just plain simple JavaScript and cute jQuery is more than enough.

On the logout page, we can try to close the window using JavaSript or write any message.

Feel free to download the source code from download link at the top.

Hope you liked this article, do share to your friends, colleagues and social websites by clicking on the social link below.
Recommendation
Read Using Angular $http.put with ASP.NET MVC project after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Amatya on: 7/23/2015 | Points: 25
Nice 1

Login to post response

Comment using Facebook(Author doesn't get notification)