带有Identity的ASP.NET Core 2.0中的Cookie过期

时间:2017-08-25 06:31:49

标签: asp.net .net asp.net-core asp.net-identity asp.net-core-2.0

环境:ASP.NET Core 2.0,带有cookie的身份。

Startup.ConfigureServices()中有这样的:

services.ConfigureApplicationCookie(options => {
  options.ExpireTimeSpan = TimeSpan.FromDays(14);
  options.Cookie.Expiration = TimeSpan.FromDays(14);
});

第一个来自CookieAuthenticationOptions。第二个来自CookieBuilder。文档还提到Microsoft.AspNetCore.Http.CookieOptions.Expires(虽然它在该lambda中不可用)。

这些有什么区别?在Core2中设置到期时间的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

以下是我用来设置我使用的测试应用程序中cookie的到期时间。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        ...

        ...  // before services.AddMvc();!
        services.AddAuthentication().AddCookie(options => {
            options.Cookie.Expiration = TimeSpan.FromDays(14);
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
            options.Cookie.Name = "MyCookieName";
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/Forbidden";
        });

        // OR Perhaps, this could be what you need
        services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
            options.Cookie.Name = "MyCookieName";
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/Forbidden";
        });
        ...
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ... // before app.UseMvc();!
        app.UseAuthentication();
        // WAS -> app.UseCookieAuthentication();
        ...
    }
    ...
}

我认为这应该让你朝着正确的方向前进。

这对我有用,我还没有发现任何问题。虽然,自Core 2.0 RTM起仅仅几周了。 :)

希望这有帮助。

答案 1 :(得分:1)

这段代码适合我。只有第二个块会更改cookie过期

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.Cookie.SameSite = SameSiteMode.Strict;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.LoginPath = "/Account/Login";
            options.LogoutPath = "/Account/Logout";
            options.AccessDeniedPath = "/Account/AccessDenied";
        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings, only this changes expiration
            options.Cookie.HttpOnly = true;
            options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.ExpireTimeSpan = TimeSpan.FromDays(150);
        });