.NET Core 2 CookieAuthentication忽略到期时间跨度

时间:2018-06-03 20:24:41

标签: asp.net asp.net-mvc asp.net-core asp.net-core-2.0 asp.net-authentication

我正在使用CookieAuthentication处理.NET Core 2.1 Web应用程序。由于某些原因,在ExpireTimeSpan对象上设置Cookie.ExpirationCookieAuthenticationOptions并不会影响Cookie生命周期。 Chrome始终显示相同的到期日期1969-12-31T23:59:59.000Z。因此,在关闭浏览器窗口后,cookie就消失了。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
   services.AddDistributedMemoryCache();

   services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options =>
      {
         options.LoginPath = new PathString("/Account/Login/");
         options.AccessDeniedPath = new PathString("/Account/Login/");
         options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
         options.Cookie.Expiration = TimeSpan.FromDays(14);
         options.ExpireTimeSpan = TimeSpan.FromDays(14);
      });

   services.AddMvc(options =>
   {
      options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
   });

   services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   if (env.IsDevelopment())
   {
      app.UseBrowserLink();
      app.UseDeveloperExceptionPage();
   }
   else
   {
      app.UseExceptionHandler("/Error");
   }

   var provider = new FileExtensionContentTypeProvider();
   provider.Mappings[".tag"] = "riot/tag";

   app.UseStaticFiles(new StaticFileOptions()
   {
      ContentTypeProvider = provider
   });

   app.UseAuthentication();

   app.UseMvc(routes =>
   {
      routes.MapRoute(
             name: "default",
             template: "{controller=Home}/{action=Index}/{id?}");
   });
}

登录我使用此代码

ClaimsPrincipal user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId.Value.ToString()) }, CookieAuthenticationDefaults.AuthenticationScheme));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);

我已尝试在services.AddMvc之前加services.AddAuthentication,但这并没有什么不同。我在services.ConfigureApplicationCookie之后尝试过services.AddAuthentication Cookie expiry in ASP.NET Core 2.0 with Identity

我错过了什么?

4 个答案:

答案 0 :(得分:1)

来自Use cookie authentication without ASP.NET Core Identity,以粗体显示重点。

  

TimeSpan之后存储的身份验证票据   cookie到期。将ExpireTimeSpan添加到当前创建时间   票证的到期时间。 ExpiredTimeSpan值始终为   进入服务器验证的加密AuthTicket。 也可能   进入Set-Cookie标头,但仅限IsPersistent设置。设置   IsPersistent为true,配置传递给的AuthenticationProperties   SignInAsync。 ExpireTimeSpan的默认值为14天。

答案 1 :(得分:1)

使用 IsPersistent = true

示例

                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, client.Id),
                    new Claim(ClaimTypes.Role, client.Role)
                };

                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                          new ClaimsPrincipal(identity),
                          new AuthenticationProperties
                          {
                              ExpiresUtc = DateTime.UtcNow.AddYears(1),
                              IsPersistent = true
                          });

答案 2 :(得分:1)

身份具有专用的cookie配置选项CookieAuthenticationOptions和cookie Expiration值已被决定忽略,可以在此处找到一些说明: Github issue Test reference

答案 3 :(得分:0)

Chrome中的到期日期表示浏览器中Cookie的生存期,而不是令牌的超时。将Identity Server 4与ASP.NET Identity一起使用时,此处将使用Identity Server的cookie超时。客户端令牌到期后,将根据Identity Server重新验证用户的身份,并且由于该令牌尚未过期,因此将更新客户端令牌。要在Identity Server上设置到期时间,必须在Identity Server Startup.cs中添加ConfigureApplicationCookiemiddleware,如下所示:

services.AddAuthentication();

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

services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);