C# MVC Creating a timer based auto-logout with jquery?
How do I create an jquery script to automatically log out the user after a set period of inactivity? Or is t开发者_运维问答here a jquery plugin that does this? It would need to do something like:
- Create timer with setTimeout (eg for 30 mins)
- Reset the timeout every time the user interacts with the page
- After the setTimeout expires, use ajax to call the /logout action on the server (asp.net mvc)
- Show a modal/lightbox dialog telling the user to login again
You have couple of different aspects that you need to consider here. First of all, what happens if the user just closes the browser or if the computer the person is using dies? If the user visits the page within 30 minutes, should the person still be logged in?
Let's say that the user should be logged in for 30 minutes, no matter what. The easiest way to start is to set a cookie timeout on an authentication cookie. Remember to update the timeout when each page refreshes. And use a jQuery timer to check if the cookie is still valid or not, or just keep track of the users login time.
So, jQuery timers, you could on each page load refresh the cookie and then just check if the timer/delay executes, if so, remove the cookie and display a modal box.
There's tons of ways of doing this, using the timers are one way.
$(this).oneTime(1800 , function() {
location.href='/logout'; // redirects to logout page.
});
Another aproach is to use server side checking for this, but you will not get the model box for this, as I said, there are tons of ways, it all depends on your preferences.
I know it's very old question, but could be useful for someone looking for similar solution to log out user if they are idle for certain timeperiod
http://www.dotnetfunda.com/articles/show/3130/automatically-logout-when-user-is-idle-for-sometime
The link may disappear so here is the code -
<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();
精彩评论