Cookies 在基于声明的身份验证上设置cookie的过期时间
我得到了一个标准的MVC5网络应用程序,从模板上进行了一些修改 我试图在我登录时创建的cookie上设置30分钟的过期时间 这是我的登录操作Cookies 在基于声明的身份验证上设置cookie的过期时间,cookies,asp.net-mvc-5,claims-based-identity,Cookies,Asp.net Mvc 5,Claims Based Identity,我得到了一个标准的MVC5网络应用程序,从模板上进行了一些修改 我试图在我登录时创建的cookie上设置30分钟的过期时间 这是我的登录操作 [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { var user =
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
var user = AccountDomain.CheckUserLogin(model.UserName, model.Password);
if (user != null)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var claims = new List<Claim>
{
new Claim("UserName", user.UserName),
new Claim("FirstName", user.FirstName ?? ""),
new Claim("LastName", user.LastName ?? "")
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var claimsPrincipal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = claimsPrincipal;
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, identity);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
return View(model);
}
但是cookie声明过期:当浏览会话结束时
如果在登录页面上选中“记住我”,则iPersistent将为true,并将cookie的过期时间设置为登录后14天
如何手动设置cookie的过期时间?您应该有一个StartUp.cs配置文件,其中包含以下代码:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
ExpireTimeSpan = TimeSpan.FromDays(5),
SlidingExpiration = true
}
});
ExpireTimeSpan使您能够手动设置过期时间。ExpireTimeSpan将为持续登录设置过期时间。但是,如果您希望支持这两种类型的登录,则这不是您想要的。以下是一个适用于正常登录且不会破坏持久登录的解决方案:在Startup.Auth.cs中设置ExpireTimeSpan,如下所示
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
xxx...
},
ExpireTimeSpan = TimeSpan.FromDays(7),
SlidingExpiration = false
ExpireTimeSpan应位于提供程序之外。
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
xxx...
},
ExpireTimeSpan = TimeSpan.FromDays(7),
SlidingExpiration = false