【发布时间】:2018-11-13 04:52:23
【问题描述】:
我正在使用CookieAuthentication 开发一个 .NET Core 2.1 Web 应用程序。由于某种原因,在CookieAuthenticationOptions 对象上设置ExpireTimeSpan 和Cookie.Expiration 不会影响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.AddAuthentication 之后尝试过services.ConfigureApplicationCookie,就像这个答案Cookie expiry in ASP.NET Core 2.0 with Identity
我错过了什么?
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-core asp.net-core-2.0 asp.net-authentication