The common model for session handling in web forms during a post back is always to check whether a the page sessions is still in-memory, else some practical redirection to a login page would always occur. I usually did it this way via the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count == 0)
Response.Redirect("Login.aspx");
else
{
if (!IsPostBack)
{
//continuing code here
}
}
}
At some point, I was not contented with this model. The rationale was simple: prevent unauthorized users from using the existing authentication if and when the valid user has left his/her computer idle on a certain period of time. I also wanted to do this in the client to save me a couple of potential roundtrips. I was developing for a kiosk at that time, a kiosk that had a rich transactional user interaction. A touch-screen kiosk without a mouse. Development time was limited so I had to do with asp.net. I wanted to capture idle time in an asp.net web form but I knew it would not be possible coding it in the server-side. I turned to javascript in “detecting” inactivity in the browser.
I had come up with this relatively simple function (IdleDetect.js):
var seconds=10; //..adjust accordingly
function countDown() {
if (seconds <= 0)
{
alert('Time\'s up!');
//..client side redirection to a login page
}
seconds--;
window.setTimeout("countDown()",1000);
}
function resetCounter()
{
seconds=10;
alert('timer has been reset!');
countDown();
}
By itself, it’s not really detecting any idle activity. However, the client logic is already ready for plumbing in the HTML DOM.
<head runat="server">
<title>Idle Time</title>
<script
type="text/javascript"
language="javascript" src="IdleDetect.js"></script>
</head>
<body onload="countDown();"
onkeydown="alert('keydown');">
<form id="form1" runat="server" onmousemove="alert('mousemove');">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div onmousemove="resetCounter();">
<!-- form elements, etc -->
</div>
</form>
</body>
Tests show that the cool thing about this code is that a user touching the screen is tantamount to a “mousemove” JavaScript event. Implementing browser window idle detection creates the effect that the stateless web page is “listening” to an event similar to the winforms model.