'Logout user after a set period of inactivity for angular embedded in asp.net mvc application
I have asp.net MVC 4.8 enterprise application which having 60% angular component code and 40% C#, cshtml page.
Application having owin cookies based authentication, let say it has managed to log out in 2 min.
IAppBuilder.CookieAuthenticationOptions.ExpireTimeSpan =2 minutes
Scenario:
- If a user has opened angular page and idle for more than 2 min, login page not been re-directed automatically.
- If a user has opened asp.net mvc page and idle for more than 2 min, login page get redirected automatically.
- If a user has opened angular page and page having background api call for every 5 seconds , login page not been re-directed at all.
- If a user has opened asp.net mvc page and page having background api call for every 5 second, login page not been re-directed at all.
As solution : I have implemented below code in common javascript file
var USER_INACTIVE_SINCE = 0;//IN MINUTE
var IDLE_TIME_ALLOWDED = 10;//IN MINUTES
function checkUsersActivity() {
setInterval(function () {
USER_INACTIVE_SINCE += 1;
}, (1000 * 60));//1 MINUTE INTERVAL
$(window).focus(function () {
USER_INACTIVE_SINCE = 0;
});
$(window).blur(function () {
USER_INACTIVE_SINCE = 0;
});
$(document).click(function () {
USER_INACTIVE_SINCE = 0;
});
$(document).keypress(function () {
USER_INACTIVE_SINCE = 0;
});
}
function IsUserActive() {
return IDLE_TIME_ALLOWDED > USER_INACTIVE_SINCE;
}
to stop background call let say in 1 min in case of user inactive below code has been implemented in each and every file.
this.intervalTime = setInterval(() => {
if (IsUserActive()) {
this.CheckUserOnline(); //api call
}
}, 5000); //every 5 seconds
Problem : Using above implementation I have managed all scenario except user experience. until and unless user doesn't click on page (which have background api call) after idle time (let say 2 min) login page doesn't get redirected automatically.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
