Search code examples
c#asp.netasp.net-mvcsessionasp.net-identity-2

My user isn't logged out after the session expires using asp.net identity 2.0


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.

  1. The user isn't redirected to the login page
  2. The session still contains some of the user details in the claim
  3. The session is missing other custom information from the claim that is not part of the identity framework

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

enter image description here

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"
            });

Solution

  • 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)
        });