Increasing session timeout to a week or more
Asked Answered
B

3

14

In order to increase session timeout, it appears I would use the following setting:

<system.web>
  <sessionState mode="InProc" timeout="20" />
  /* Etc... */
</system.web>

Here the timeout is set to 20 minutes (the default value). And, apparently, the maximum value is 525,600 minutes, or one year.

I can come back to Facebook a week later and I'm still logged in. This is how I want my application to behave. But according to this answer, this can adversely affect performance because "your inactive sessions will remain in Web server memory which may cause application pool to recycle, which would result in loosing all sessions for all users."

Does anyone know the details about this performance hit? And, if it's for real, is there a more performant way to keep users logged in like sites such as Facebook?

UPDATE:

Below is the relevant section of my current web.config file.

<system.web>
  <authentication mode="None" />
  <sessionState mode="InProc" timeout="60" />
  <compilation debug="true" targetFramework="4.6" />
  <httpRuntime targetFramework="4.5.2" executionTimeout="240" maxRequestLength="20480" />
  <httpModules>
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
  </httpModules>
  <customErrors mode="Off"></customErrors>
</system.web>
<system.webServer>
  <modules>
    <remove name="FormsAuthentication" />
    <remove name="ApplicationInsightsWebTracking" />
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
  </modules>
  <validation validateIntegratedModeConfiguration="false" />
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="20971520" />
    </requestFiltering>
  </security>
</system.webServer>

UPDATE 2:

Looks like I was incorrectly conflating two issues (authentication and session state). I apologize for not correctly sorting through some issues I was Googling on. My goal is only to extended the length of time a user is logged in.

Bolger answered 19/8, 2017 at 15:0 Comment(14)
I bet Facebook is not keeping a server side version, it’s quite stateless, they (might) get a request with an auth cookie and then dispatch the responseAlbertson
In aspnet a Cookie is created, then when you return to the site you are automatically logged in and you would normally recreate the specific user Session.Meingolda
IMHO you're confusing the ASP.NET "session" concept (used to save state on the server, possibly persisted in a DB) with authentication/login. ASP.NET also supports auth with cookie etc. that can last much longer (years), like any other site. In general, when you do this, the ASP.NET session is optional. You can reload relevant user info from the DB, use cache,etc.Germany
@SimonMourier I think you might be on to something there. It's the authentication I want to extend.Bolger
How do you do auth then?Germany
@YvetteColomb - well, they really are two different things. ASP.NET Session is not auth (by default, it relies on an automatic guid-like-that-you-cannot-guess cookie), it's a state bag created for the current connected thing/stuff/whatever. Auth is another process that Jonathan needs to setup according to his contextGermany
@SimonMourier I'm using Visual Studio 2017. When creating my app, I selected Individual User Accounts. So a better question might be how does Visual Studio do authentication.Bolger
@YvetteColomb Perhaps I was conflating authentication with session state. My concern is with authentication. Authentication is working just fine now. But as in my original question, I want to keep users logged in for a week or so.Bolger
@YvetteColomb If you want to criticize how I formulated the question, then have at it. But in the original question I stated I can come back to Facebook a week later and I'm still logged in. This is how I want my application to behave. That is still what I want.Bolger
You should be able to go in the Code\Startup.Auth.cs and modify the definition of CookieAuthenticationOptions, add ExpireTimeSpan=what you want. And if you don't use ASP.NET session, you should remove it entirely (Off)Germany
@JonathanWood just for clarification as I am just getting updated with all the comments and question clarification. Your requirement is to have the user logged in for a week? correct? Are you using asp.net.identify?Agostino
@JonathanWood also what version of asp.net-mvc is the project? 5.* or coreAgostino
@JonathanWood Could you show us the code how you authenticate user?Spear
@Spear I'm not sure what part you are interested in. I just created a new MVC project in Visual Studio 2017 and am using what was created automatically for me.Bolger
O
6

For Login, you must use FormsAuthentication or ASP.NET Identity (Improved version of cookie based authentication over FormsAuthentication) which allows you to keep authentication cookie for more then weeks/months. FormsAuthentication is stateless, and in order to support multiple servers, you can use single machineKey in all servers. All samples and tutorials mostly guide to use FormsAuthentication by default.

Faceboook and everyone use authentication cookie, no body uses Session for login.

Ideally Session is bad and mostly unnecessary. It can be replaced with HttpRuntime.Cache. Cache can be easily setup to use some external provider such as Fabric cache or Redis. To make cache isolated by user, you can simply append keys of cached item with username.

UPDATE

There is no downside in using FormsAuthentication except that there is little CPU overhead required in decrypting cookie, but that can also be avoided by caching authentication ticket.

The only reason to support Session could be compatibility with old ASP application they might be supporting.

In the new ASP.NET MVC sample, they have configured cookie based authentication in code (in startup), which is not session. Though session is configured in web.config but as long as you don't want to store anything in session, you can completely disable it.

Ostensory answered 21/8, 2017 at 15:47 Comment(10)
I've updated my question with the relevant section of my web.config. It doesn't appear to be using Forms Authentication. Do you know why MVC configures it that way? Is there a downside to using Forms Authentication that I need to know about?Bolger
The only reason to support Session could be compatibility with old ASP application they might be supporting. There is no downside with FormsAuthentication, it is most recommended solution.Ostensory
Thanks for responding, but the latest version of MVC initializes using the settings I have now. If it's the most recommended solution, why is Microsoft defaulting to something else?Bolger
@JonathanWood Even if session is configured, doesn't mean it should be used for login, you can still store something in session, most likely no body removed it in examples, and people still use session, but not for login. Only rare important secret information which they can't store in cookies.Ostensory
Thanks again but there is something I must be missing. I haven't changed anything with the authentication configuration from what was added by the Visual Studio 2017 project wizards. So before I can assure myself that I don't have it configured right, I need to understand why Microsoft doesn't have it configured right.Bolger
Which authentication type did you choose?Ostensory
I selected Individual User Accounts.Bolger
I checked sample, Microsoft is using Identity SignInManager, which is more advanced then FormsAuthentication which basically includes two factor auth etc, check #33085903 , however, this is still not Session.Ostensory
Thanks for the input but ASP.NET Identity is Microsoft's new authentication component. Forms Authentication is the old one. It doesn't make sense to me that I need to use the old one.Bolger
No you don't need to use old one, you can use Identity, it is configured already in your code, what I mean Identity is also not dependent on Session.Ostensory
A
2

Created a stock MVC project from scratch with Individual User Account selected for Auth.

Startup.Auth.cs

public partial class Startup {
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app) {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            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(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            },
            ExpireTimeSpan = TimeSpan.FromDays(7)//<-- I just added this.
        });

        //...code removed for brevity
    }
}
// Summary:
//     Controls how much time the cookie will remain valid from the point it is
//     created. The expiration information is in the protected cookie ticket. Because
//     of that an expired cookie will be ignored even if it is passed to the server
//     after the browser should have purged it
public TimeSpan ExpireTimeSpan { get; set; }

Changed nothing else in the project and the default template provided everything needed.

UPDATE

Based on comments, you could always add it as a app setting in web.config and use ConfigurationManager to access it. That way it can be modified without having to recompile code.

var expireTimeSpan = TimeSpan.FromDays(7);//the default
var setting = ConfigurationManager.AppSettings["ApplicationCookieExpireTimeInDays"];
if (setting != null) {
    var days = 0;
    if (int.TryParse(setting, out days)) {
        expireTimeSpan = TimeSpan.FromDays(days);
    }
}

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    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(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    },
    ExpireTimeSpan = expireTimeSpan
});

Where web.config would hold the setting.

<appSettings>
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="ApplicationCookieExpireTimeInDays" value="14" />
</appSettings>
Agostino answered 21/8, 2017 at 16:54 Comment(10)
Do you have any information about the ramifications of changing Visual Studio's settings to using forms authentication? I had trouble finding a clear description of this and I'm still confused why the way Microsoft set it up isn't good enough. Does that break or even affect my existing authentication? I am not using .NET core. Of course, I just want to configure in web.config.Bolger
I basically followed the stock templates and modified to suit custom scenarios. following their online resources. learn.microsoft.com/en-us/aspnet/identity/overview/…Agostino
@JonathanWood I did not quite understand what you mean by the ramifications of changing Visual Studio's settings to using forms authentication can you clarify.Agostino
@Agostino I'm using the latest version of Visual Studio and it configured this for me. Now your answer suggests it should be configured differently. That can only make me wonder why Microsoft did it this way if it should be configured differently. And I yet have a good enough understanding to conclude that Microsoft's way is not the right way.Bolger
@Nkosi: Note that I'm not looking to change anything that I don't need to. I just want to change how long a user stays logged in. If you're saying that required Forms Authentication, then I need to understand why Microsoft does not use Forms Authentication by default.Bolger
@JonathanWood depending on the project template you choose. What I have in my answer was provided by MS with minor changes by me. For example their timeout for the cookies was way shorter than what I updated it do.Agostino
@JonathanWood I just created an stock mvc application and selected Individual user acount as the Auth. Only had to add the ExpireTimeSpan to the CookieAuthenticationOptions in Startup.Auth.cs and I was done. touched nothing else. My initial example was for demonstration purposes only.Agostino
@Agostino Then that would be exactly what I was looking for. (Although I suspect there's a web.config setting for this.) Will test shortly.Bolger
@JonathanWood, You could always add it as a app setting in web.config and use ConfigurationManager to access it. That way it can be modified without having to recompile code.Agostino
@Agostino I've spent some time playing with this. I can see that the default value for ExpireTimeSpan is 14 days. So it's hard to see how that solves the issue of users being logged out in 10 -20 minutes.Bolger
P
1

The answer you cite is partially true. It depends on where the session state is stored.

There should be no issue with increasing the session state when storing the session state in the SQL Server database. Also using Web Farms - which makes sense to cater for scalability.

From this article:

Storing Session State in a SQL Server Database

Storing session variables in the SQL server has the following advantages:

Scalability: If you are looking for a highly scalable option to store your session variables, the SQL Server option is for you. It is a much more scalable option than the others. Web farm architecture can very easily access the session variables because they are stores in an independent database.
Reliability: Because the data is physically persisted in a database, it is is more reliable than the other options. It has the ability to survive server restarts.
Security: SQL Server is more secure than the in-memory or state server option. You can protect your data more easily by configuring SQL Server security.

It's an old article, but these principles still apply.

There can be issues when using memory of the Web Server.

How does increasing the session timeout effect the application performance and why?

If you extend the duration of Sessions, any items held in session variables will stay in memory on the server longer. Depending on how busy your application is, and the type and number of items you persisits as session variables, this may degrade performance.

copied in the typo from the quote.

This question also discusses the difference between session state and the use of cookies with FormsAuthentication.

Should I use Session State or FormAuthentication to keep track of a signed-in user?

So depending on what type of authentication you are using - you may go the cookie route, bearing in mind the user can delete the cookie from the browser and this will log them out.

This is another helpful link to the docs.

Securing Session State

Phylloid answered 21/8, 2017 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.