'.NET Framework change cookie expiration based on user role
In our Startup.cs file, we are configuring our CookieAuthentication as seen below:
if (!int.TryParse(ConfigurationManager.AppSettings["LoginTimeout"], out int timeout)) timeout = 60;
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = TimeSpan.FromMinutes(timeout),
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
And my AccountController code is:
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
// do stuff
return RedirectToLocal(returnUrl);
}
My question is: how can I change the ExpireTimeSpan based on the user's role? Is this something that needs to be configured in the startup class? Or can it be done in the Account Controller after the user has been signed in?
Solution 1:[1]
After many hours of searching, I came across how to do this. In my application, we redirect the user to a dashboard upon successful login. In the page load method, we check the user to see if they have the Administrator role, and if they do, this is what you do:
public ActionResult Index()
{
if (User.IsInRole("Administrator"))
{
HttpCookie cookie = HttpContext.Request.Cookies.Get(".AspNet.ApplicationCookie");
cookie.Expires = DateTime.Now.AddHours(12);
Response.Cookies.Set(cookie);
return RedirectToAction("BusinessIndex");
}
// other checks
}
It is important to note that this cannot be done in the AccountController under the case SignInStatus.Success: condition as the cookie has not actually been issued yet.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Timothy Sutton |
