I have an application built using MVC 5, we have a scenario where users are redirected to the login page when the default session timeout has elapsed even while the user was still typing on a text box. I want users to be redirected to login page only when a page has been left idle for more than 15 minutes but not when users are very. In web forms, we use to set sliding expiration to true in the config file, but that doesn't work in MVC. I will appreciate any assistance.
What I have tried:
Login Action:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginViewModel model, string returnUrl, string command)
{
string decodedUrl = "";
if (!string.IsNullOrEmpty(returnUrl))
decodedUrl = Server.UrlDecode(returnUrl);
FormsAuthentication.SetAuthCookie(model.Email, false);
var authTicket = new FormsAuthenticationTicket(1, user.Email,
DateTime.Now, DateTime.Now.AddMinutes(15), false, user.Roles);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
HttpContext.Response.Cookies.Add(authCookie);
authCookie.Expires = authTicket.Expiration;
if (Url.IsLocalUrl(decodedUrl))
{
return Redirect(decodedUrl);
}
else
{
return RedirectToAction("analytics", "dashboard");
}
}
Global ASAX Code:
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
try
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}
catch(Exception ex)
{
}
}