我有一个标准的MVC5网络应用程序,其中有一些来自模板的修改。
我尝试在登录时创建的Cookie设置30分钟到期
这是我的登录操作
[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);
}
我试过这个
var exp = new DateTimeOffset().AddMinutes(5);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe, ExpiresUtc = exp }, identity);
但cookie表示过期:浏览会话结束时
如果在登录页面上选中了“记住我”,则IsPersistent将为true,并将cookie的有效期设置为登录时间的14天。
如何手动设置cookie的到期时间?
答案 0 :(得分:0)
你应该有一个StartUp.cs配置文件,其中包含以下代码:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
ExpireTimeSpan = TimeSpan.FromDays(5),
SlidingExpiration = true
}
});
ExpireTimeSpan 让您手动设置过期时间。
答案 1 :(得分:0)
ExpireTimeSpan将设置持久登录的到期时间。但是,如果要支持这两种类型的登录,则不是您想要的。这是一个适用于正常登录的解决方案,不会破坏持久登录:User logout after non-persistent login in Asp.Net Identity 2
答案 2 :(得分:0)
在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