asp.netasp.net-mvcasp.net-coreasp.net-core-2.0asp.net-authentication

.NET Core 2 CookieAuthentication ignores expiration time span


I'm working on a .NET Core 2.1 Web application with CookieAuthentication. For some reason setting the ExpireTimeSpan and Cookie.Expiration on the CookieAuthenticationOptions object doesn't have an effect on the Cookie lifetime. Chrome always displays the same expiration date of 1969-12-31T23:59:59.000Z. So after closing the browser window the cookie is gone.

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

On SignIn I'm using this code

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

I've tried putting services.AddMvc before services.AddAuthentication but it doesn't make a difference. I've also tried services.ConfigureApplicationCookie after services.AddAuthentication like in this answer Cookie expiry in ASP.NET Core 2.0 with Identity

What am I missing?


Solution

  • Use IsPersistent = true

    Example

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