Share via


Bigger session timeout in ASP.net 4.5.2

Question

Tuesday, April 30, 2019 10:22 AM

Hello, I am a new developer,

I've been handled an old project written in ASP.net 4.5.2.

I have to fix a session problem, people get automatically logged off after 20 minutes and I can't figure why. I have to disable this because it's annoying and people want to be logged in for hours without being kicked out.

I've been reading a variety of guides but can't manage to debug (What's the best way to verify this!? I can't just sit around more than 20 minutes to test this!) the problem and figure out how to change the timeout.

http://www.dedicatedsqlserver.com/HowTo/IIS_Timeout.aspx

I tried editing web.config without luck. Any suggestion? I can't physically access the web server running IIS, I can ask for access but I'd love to try some local solutions first.

Thank you :)

All replies (9)

Tuesday, April 30, 2019 10:50 AM

Authentication generally uses an authentication cookie not Session.  Are you sure Session is used to cache user credentials?  Can you explain how the security works?


Tuesday, April 30, 2019 10:58 AM

Hello and thanks for the reply,

the project uses the default identity and account management (using the default ApplicationUserManager), nothing fancy. I've been asked to "check" the session but it may very well somewhere else the problem.

Can you point me to the right files I should be looking at?

From App_Start/IdentityConfig.cs, this is my ApplicationManager and SignInManager:

// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = 
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    
// Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }

Also, in my web.config file:

 <system.web>
    <authentication mode="None" />
  </system.web>

  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

I'm so confused. I have no idea what's going on with all of this.


Tuesday, April 30, 2019 11:24 AM

OWIN Identity Configuration.

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                ExpireTimeSpan = TimeSpan.FromMinutes(60),
                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, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(60),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            }); 

Tuesday, April 30, 2019 11:30 AM

This is the pre-existing Startup.Auth.cs (as a noob dev who only worked with the Core framework this file wasn't easy to find.. it's not obvious):

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                ExpireTimeSpan = TimeSpan.FromDays(2),
                SlidingExpiration = false,
                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, ApplicationUser>(
                        validateInterval: TimeSpan.FromDays(2),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }

            });     

It's already set to 2 days.


Tuesday, April 30, 2019 12:58 PM

Perhaps IIS is spinning down for lack of use.  The default app pool idle timeout is 20 minutes. 

Try setting a consistent machine key rather than auto-generated which will allow the auth cookie to get decoded if the app restarts.

https://blogs.msdn.microsoft.com/vijaysk/2009/05/13/iis-7-tip-10-you-can-generate-machine-keys-from-the-iis-manager/


Thursday, May 2, 2019 7:25 AM

Unfortunately, I have no access to the IIS server, I just have a solution with a pre-configured web-publish.

Things I tried:

  • sessionState in web.config
  • Cookie authentication in the Startup.Auth.cs file

Apart from this, my only option left is to check the IIS pool idle timeout?


Thursday, May 2, 2019 10:15 AM

Apart from this, my only option left is to check the IIS pool idle timeout?

For the second time, set a consistent machine key.  You can use IIS on your machine to create the key.


Thursday, May 2, 2019 10:58 AM

For anyone, like me, confused by @mgebhard replies:

https://forums.asp.net/t/1731352.aspx?What+is+machinekey+

https://forums.asp.net/t/1857989.aspx?Session+timeout+problem

Basically (unless I set one specifically in my web.config file) when the application pool recycles due to inactivity IIS generates a new machine key and invalidates all previous cookies?

EDIT:

Some machine key generators


Friday, May 3, 2019 7:51 AM

Hi Fieel

   ExpireTimeSpan = TimeSpan.FromMinutes(60),

According to your description, how do you login your account? The way you login the account might cause ExpireTimeSpan to be no use.

Then when you set the code for persistent type for cookie,I suggest you could set IsPersistent as true.

   AuthManager.SignIn(new AuthenticationProperties { IsPersistent = true }, ident);   

Here is the link , I hope it could help you.

https://forums.asp.net/t/2121970.aspx?OWIN+Authentication+ExpireTimeSpan+not+working

Best Regards

Wei