我正在尝试为我的aspnet core 2.0网站实现登录表单。 我设置了14天的持久性,但30分钟后,Identity.User.IsAuthenticathed属性返回False
我的statup类:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(14);
});
var servConfiguration = Configuration.GetSection("ServConfiguration");
services.Configure<ServConfigurationModel>(servConfiguration);
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseAuthentication();
app.UseCookiePolicy(new CookiePolicyOptions()
{
MinimumSameSitePolicy = SameSiteMode.Lax,
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我的登录方式:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login([FromForm] LoginModel loginData)
{
if (!ModelState.IsValid)
{
logger.LogWarning("invalid login data username: " + "Username: " + loginData.Username);
return View();
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginData.Username)
};
var claimsIdentity = new ClaimsIdentity(
claims,
CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(principal, new AuthenticationProperties()
{
IsPersistent = true,
AllowRefresh = true
});
}
我的登录检查
[HttpGet]
public async Task<IActionResult> LoginCheck()
{
if (User.Identity.IsAuthenticated)
{
logger.LogInformation("user is authenticated");
}
else
{
logger.LogInformation("user is not authenticated");
}
return View();
}
请注意:aspnet cookie有正确的过期,但是如果我在网站上返回30分钟后用户仍然没有登录。