Asp.net

.NET Core 2 CookieAuthentication 忽略過期時間跨度

  • December 17, 2020

我正在使用 .NET Core 2.1 Web 應用程序開發CookieAuthentication. 由於某種原因,在對像上設置ExpireTimeSpanand不會影響 Cookie 的生命週期。Chrome 始終顯示相同的到期日期。所以關閉瀏覽器視窗後cookie就消失了。Cookie.Expiration``CookieAuthenticationOptions``1969-12-31T23:59:59.000Z

啟動.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.AddMvcservices.AddAuthentication但沒有什麼不同。我也在這個答案中services.ConfigureApplicationCookie嘗試過Cookie expiry in ASP.NET Core 2.0 with Identityservices.AddAuthentication

我錯過了什麼?

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

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

.net core 3.1 的更新(cooke.expiration 不再需要作為單獨的選項):

services.AddAuthentication();

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

services.AddMvc();

引用自:https://stackoverflow.com/questions/50670654