asp.net-mvc ASP.NET Core MVC:设置身份 cookie 的过期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34979680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:31:29  来源:igfitidea点击:

ASP.NET Core MVC: setting expiration of identity cookie

asp.net-mvcasp.net-identityasp.net-coreasp.net-core-mvc

提问by severin

In my ASP.NET Core MVC app the lifetime of the authentication cookie is set to 'Session', so it lasts until I close the browser. I use the default authentication scheme for MVC:

在我的 ASP.NET Core MVC 应用程序中,身份验证 cookie 的生命周期设置为“会话”,因此它一直持续到我关闭浏览器。我使用 MVC 的默认身份验证方案:

app.UseIdentity();

How can I extend the lifetime of the cookie?

如何延长 cookie 的生命周期?

回答by user1620696

The ASP.NET Identity middleware which you are using is a wraper around some calls to UseCookieAuthenticationwhich includes the Cookie Authentication middleware on the pipeline. This can be seen on the source code for the builder extensions of the Identity middleware here on GitHub. In that case the options needed to configure how the underlying Cookie Authentication should work are encapsulated on the IdentityOptionsand configured when setting up dependency injection.

您正在使用的 ASP.NET Identity 中间件是一些调用的包装器,UseCookieAuthentication其中包括管道上的 Cookie 身份验证中间件。这可以在 GitHub 上的 Identity 中间件的构建器扩展的源代码中看到。在这种情况下,配置底层 Cookie 身份验证应该如何工作所需的选项被封装在IdentityOptions设置依赖注入时配置和配置。

Indeed, looking at the source code I linked to you can see that the following is run when you call app.UseIdentity():

确实,查看我链接到的源代码,您可以看到调用时会运行以下内容app.UseIdentity()

var options = app.ApplicationServices.GetRequiredService<IOptions<IdentityOptions>>().Value;
app.UseCookieAuthentication(options.Cookies.ExternalCookie);
app.UseCookieAuthentication(options.Cookies.TwoFactorRememberMeCookie);
app.UseCookieAuthentication(options.Cookies.TwoFactorUserIdCookie);
app.UseCookieAuthentication(options.Cookies.ApplicationCookie);
return app;

To setup the IdentityOptionsclass, the AddIdentity<TUser, TRole>method has one overloaded version which allows to configure the options with one lambda. Thus you just have to pass in a lambda to configure the options. In that case you just access the Cookiesproperties of the options class and configure the ApplicationCookieas desired. To change the time span you do something like

为了设置IdentityOptions类,该AddIdentity<TUser, TRole>方法有一个重载版本,允许使用一个 lambda 配置选项。因此,您只需要传入一个 lambda 来配置选项。在这种情况下,您只需访问Cookies选项类的属性并ApplicationCookie根据需要进行配置。要更改时间跨度,您可以执行以下操作

services.AddIdentity<ApplicationUser, IdentityRole>(options => {

    options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1);

});

EDIT:The ExpireTimeSpanproperty is only used if when calling HttpContext.Authentication.SignInAsyncwe pass in an instance of AuthenticationPropertieswith IsPersistentset to true.

编辑:ExpireTimeSpan属性仅在调用时HttpContext.Authentication.SignInAsync传入AuthenticationPropertieswith IsPersistentset to的实例时才使用true

Trying out just with the Cookie Authentication Middleware it turns out that this works: if we just sign in without this option, we get a cookie that lasts for the session, if we send this together we get a cookie which lasts what we setup when configuring the middleware.

仅使用 Cookie 身份验证中间件进行尝试,结果证明这是有效的:如果我们在没有此选项的情况下直接登录,我们将获得一个持续会话的 cookie,如果我们将其一起发送,我们将获得一个持续时间配置时设置的 cookie中间件。

With ASP.NET Identity the way to do is pass the parameter isPersistentof the PasswordSignInAsyncwith value true. This ends up being a call to SignInAsyncof the HttpContextpassing in the AuthenticationPropertieswith the IsPersistentset to true. The call ends up being something like:

使用ASP.NET身份做的方式是传递参数isPersistentPasswordSignInAsync与价值true。这最终是要在通话SignInAsync中的HttpContext在通过AuthenticationPropertiesIsPersistent设置为true。电话最终是这样的:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

Where the RememberMeis what configures if we are setting IsPersistentto true or false.

RememberMe如果我们设置IsPersistent为 true 或 false,那么这里是什么配置。

回答by cheesemacfly

There's an answer for version 2.0 but it didn't work for me. I had to do:

2.0 版有一个答案,但它对我不起作用。我必须做:

services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromDays(30);
});

The default value is 14 days.

默认值为 14 天。

回答by Ahmed Al Jabry

For ASP.NET Core 2.0

对于 ASP.NET Core 2.0

  services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.Name = "CookieName";
            options.Cookie.Expiration = TimeSpan.FromDays(2);
        });

回答by BorisSh

In ASP.NET Core 2.0 use ExpireTimeSpan property instead of Cookie.Expiration.

在 ASP.NET Core 2.0 中,使用 ExpireTimeSpan 属性而不是 Cookie.Expiration。

services.ConfigureApplicationCookie(options =>
{   
    options.Cookie.Name = "CookieName";         
    options.ExpireTimeSpan = TimeSpan.FromHours(24);
    options.SlidingExpiration = true;               
});

From docs:

文档

Cookie.Expiration: Gets or sets the lifespan of a cookie. Currently, this option no-ops and will become obsolete in ASP.NET Core 2.1+. Use the ExpireTimeSpan option to set cookie expiration.

Cookie.Expiration:获取或设置 cookie 的生命周期。目前,此选项无操作,并将在 ASP.NET Core 2.1+ 中过时。使用 ExpireTimeSpan 选项设置 cookie 过期时间。

回答by Damien Dennehy

Try

尝试

app.UseIdentity().UseCookieAuthentication(
    new CookieAuthenticationOptions
    {
        ExpireTimeSpan = TimeSpan.FromHours(1)
    }
);

回答by Ole K

For some reason I had the issue when using SignInAsync([..], true)the cookie was never be shown in browser (and properly the login failed):

出于某种原因,我在使用SignInAsync([..], true)cookie时遇到了问题,从未在浏览器中显示(并且正确地登录失败):

So, I tried adding the UTC timezone difference into the TimeSpan of ExpireTimeSpan

所以,我尝试将 UTC 时区差异添加到 TimeSpan ExpireTimeSpan

services.AddIdentity<ApplicationUser, IdentityRole>(o =>
{
    // add TimeSpan with 5 minutes plus timezone difference from Utc time
    o.Cookies.ApplicationCookie.ExpireTimeSpan = DateTime.Now.Subtract(DateTime.UtcNow).Add( TimeSpan.FromMinutes(5) );

});

Voila! It worked and the cookie is shown with +5minexpiration only in browser.

瞧!它起作用了,并且 cookie仅在浏览器中显示+5 分钟过期。

PingBack to github.com https://github.com/aspnet/Identity/issues/766#issuecomment-253237576

ping回github.com https://github.com/aspnet/Identity/issues/766#issuecomment-253237576