将会话超时时间增加到一周或更长时间

14
为了增加会话超时时间,似乎我需要使用以下设置:

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

这里的超时时间被设定为20分钟(默认值)。而且,最大值似乎是525,600分钟,或者一年。

我可以在一周之后回到Facebook,仍然保持登录状态。这就是我希望我的应用程序所表现出来的方式。但根据这个答案,这可能会对性能产生不利影响,因为“您的非活动会话将保留在Web服务器内存中,这可能导致应用程序池重新启动,从而导致所有用户的所有会话都丢失。”

有人知道这种性能损失的详细信息吗?如果是真的,是否有更高效的方法使用户保持登录状态,例如Facebook等网站?

更新:

以下是我当前的web.config文件的相关部分。

<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>

更新2:

看起来我错误地把两个问题(身份验证和会话状态)混淆了。我很抱歉没有正确地整理一些我在谷歌上搜索的问题。我的目标只是延长用户登录的时间。


2
我敢打赌Facebook没有保留服务器端版本,它是相当无状态的。他们(可能)会收到一个带有身份验证cookie的请求,然后分派响应。 - hardkoded
1
@YvetteColomb - 嗯,它们确实是两件不同的事情。ASP.NET Session 不是身份验证(默认情况下,它依赖于一种自动的类似 guid 的 cookie,你无法猜测它),它是为当前连接的东西/物品/任何创建的状态包。Auth 是另一个过程,Jonathan 需要根据自己的上下文设置。 - Simon Mourier
1
@YvetteColomb 如果您想批评我提出问题的方式,请随意。但在原始问题中,我已经声明了“我可以在一周后回到Facebook,仍然保持登录状态。这就是我希望我的应用程序表现出来的方式。” 这仍然是我想要的。 - Jonathan Wood
1
你应该能够进入Code\Startup.Auth.cs文件并修改CookieAuthenticationOptions的定义,添加ExpireTimeSpan=你想要的时间。如果你不使用ASP.NET会话,你应该完全删除它 (Off)。 - Simon Mourier
1
@JonathanWood,你能展示一下你是如何验证用户的代码吗? - Win
显示剩余9条评论
3个回答

6

登录时,您必须使用FormsAuthenticationASP.NET Identity(比FormsAuthentication更好的基于cookie的身份验证升级版本),它允许您保留身份验证cookie超过几周/几个月。 FormsAuthentication是无状态的,为了支持多个服务器,您可以在所有服务器中使用单个machineKey。所有示例和教程通常都默认使用FormsAuthentication

Facebook和其他人都使用身份验证cookie,没有人使用Session进行登录。

理想情况下,Session是不好的并且大多数时候是不必要的。它可以用HttpRuntime.Cache替换。缓存可以轻松设置为使用一些外部提供者,如Fabric Cache或Redis。为了使缓存与用户隔离,您只需将缓存项的键附加到用户名。

更新

除了需要解密cookie而产生的一点CPU开销之外,使用FormsAuthentication没有任何缺点,但这也可以通过缓存身份验证票据来避免。

支持Session的唯一原因可能是与他们可能正在支持的旧ASP应用程序的兼容性。

在新的ASP.NET MVC示例中,他们已在代码中(在启动时)配置基于cookie的身份验证,这不是会话。虽然会话在web.config中进行了配置,但只要您不想在会话中存储任何内容,就可以完全禁用它。


我已经更新了我的问题,并附上了web.config的相关部分。它似乎没有使用表单身份验证。你知道为什么MVC要这样配置吗?使用表单身份验证有什么需要我知道的缺点吗? - Jonathan Wood
唯一支持“Session”的原因可能是兼容他们可能正在支持的旧“ASP”应用程序。使用“FormsAuthentication”的优点没有缺点,它是最推荐的解决方案。 - Akash Kava
你选择了哪种身份验证类型? - Akash Kava
我查看了示例,微软正在使用Identity SignInManager,它比FormsAuthentication更先进,基本上包括双因素身份验证等,请参见https://dev59.com/5VwY5IYBdhLWcg3wCUA7,但是这仍然不是“Session”。 - Akash Kava
不需要使用旧的方法,你可以使用 Identity,它已经在你的代码中配置好了,我的意思是 Identity 也不依赖于 Session。 - Akash Kava
显示剩余5条评论

2

我从头开始创建了一个MVC项目,并选择了个人用户账户进行身份验证。

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

在项目中没有改变其他任何东西,使用提供的默认模板就满足了所有需求。

更新

根据评论,您可以在web.config文件中添加它作为应用程序设置,并使用ConfigurationManager进行访问。这样可以在无需重新编译代码的情况下对其进行修改。

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

web.config文件将保存这些设置。

<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>

你有没有关于更改Visual Studio设置为使用表单身份验证的影响的任何信息?我很难找到一个清晰的描述,我仍然不明白为什么微软设置的方式不够好。这会破坏或甚至影响我的现有身份验证吗?我没有使用.NET Core。当然,我只想在web.config中进行配置。 - Jonathan Wood
我基本上遵循了标准模板,并根据自定义情况进行了修改,参考了他们的在线资源。https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/aspnet-identity-recommended-resources - Nkosi
1
@JonathanWood,我不太明白您所说的“更改Visual Studio设置以使用表单身份验证”的影响是什么,您能否澄清一下。 - Nkosi
@Nkosi 我正在使用最新版本的Visual Studio,并且它已经为我配置好了。现在你的回答表明它应该被不同地配置。这让我想知道为什么Microsoft会这样做,如果它应该被不同地配置。但是我还没有足够的理解来得出结论,即Microsoft的方式不是正确的方式。 - Jonathan Wood
@Nkosi 那就是我一直在寻找的。 (虽然我怀疑有一个 web.config 设置可以解决这个问题。)很快会测试。 - Jonathan Wood
显示剩余5条评论

1
你引用的回答部分正确。这取决于会话状态存储的位置。
当将会话状态存储在SQL Server数据库中时,增加会话状态应该没有问题。而且使用Web Farms也是有意义的,以满足可扩展性的需求。
来自这篇文章: 将会话状态存储在SQL Server数据库中 将会话变量存储在SQL服务器中具有以下优点:
  • 可扩展性:如果您正在寻找一种高度可扩展的选项来存储会话变量,则SQL Server选项适合您。它比其他选项更具可伸缩性。Web农场架构可以非常容易地访问会话变量,因为它们存储在独立的数据库中。
  • 可靠性:因为数据在数据库中物理持久化,所以它比其他选项更可靠。它具有在服务器重新启动后生存的能力。
  • 安全性:SQL Server比内存或状态服务器选项更安全。您可以通过配置SQL Server安全性更轻松地保护数据。

这是一篇旧文章,但这些原则仍然适用。

在使用Web服务器的内存时可能会出现问题。

增加会话超时时间如何影响应用程序性能?为什么?

如果您延长会话的持续时间,任何保存在会话变量中的项目将在服务器上的内存中停留更长时间。根据您的应用程序有多繁忙,以及作为会话变量持久化的项目的类型和数量,这可能会降低性能。

从引用中复制错别字。

此问题还讨论了会话状态与使用FormsAuthentication的cookie之间的区别。

我应该使用会话状态还是FormAuthentication来跟踪已登录的用户?

因此,根据您使用的身份验证类型-您可以选择cookie路线,记住用户可以从浏览器中删除cookie,这将使他们注销。

这是文档的另一个有用链接。

保护会话状态


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接