I have a MVC application using Identity 2 for authentication. After I log in, if I close the browser and then open the application again, there are 3 problems occurring.
I am using IIS to run the application on a Windows Server, but I can reproduce the issue on my local dev environment
Both the session in the cookie and on the server are set to expire after 1 minute while I am debugging the issue
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString(url.Action("LogIn","Auth")),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromMinutes(1),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
CookieName = "MyApplication"
});
The issue was that I never set the cookie to expire, adding the following 2 lines fixed the issue I was having
SlidingExpiration = true,
ExpireTimeSpan = TimeSpan.FromMinutes(30)
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString(url.Action("LogIn","Auth")),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
},
CookieName = "MyApplication",
SlidingExpiration = true,
ExpireTimeSpan = TimeSpan.FromMinutes(30)
});