Jen*_*kie 5 c# cookies asp.net-mvc asp.net-identity
我使用asp.net identity 2.0来管理用户登录.我正在关注Identity 2.0的示例,并且在整个浏览器关闭后无法使cookie保持不变.这种情况发生在所有浏览器上.
码:
账户管理员
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await SignInHelper.PasswordSignIn(model.Email, model.Password, isPersistent: true, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
SignInHelper
public async Task<SignInStatus> PasswordSignIn(string userName, string password, bool isPersistent, bool shouldLockout)
{
var user = await UserManager.FindByNameAsync(userName);
if (user == null)
{
return SignInStatus.Failure;
}
if (await UserManager.IsLockedOutAsync(user.ID))
{
return SignInStatus.LockedOut;
}
if (await UserManager.CheckPasswordAsync(user, password))
{
// password verified, proceed to login
return await SignIn(user, isPersistent);
}
if (shouldLockout)
{
await UserManager.AccessFailedAsync(user.ID);
if (await UserManager.IsLockedOutAsync(user.ID))
{
return SignInStatus.LockedOut;
}
}
return SignInStatus.Failure;
}
Run Code Online (Sandbox Code Playgroud)
-
private async Task<SignInStatus> SignIn(User user, bool isPersistent)
{
await SignInAsync(user, isPersistent);
return SignInStatus.Success;
}
Run Code Online (Sandbox Code Playgroud)
-
public async Task SignInAsync(User user, bool isPersistent)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
AuthenticationManager.SignIn(
new AuthenticationProperties
{
IsPersistent = isPersistent
},
userIdentity
);
}
Run Code Online (Sandbox Code Playgroud)
Startup.Auth
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieName = "ApplicationCookie",
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = System.TimeSpan.FromMinutes(180), // 3 hours
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (user) => (user.GetGuidUserId()))
}
});
Run Code Online (Sandbox Code Playgroud)
对不起代码墙,但是我看不出我做错了什么,当浏览器关闭而没有手动注销时,cookie不会持续3小时?
问题在于OnValidateIdentity中的一个错误,当重新生成cookie时,它总是将IsPersistent设置为false(即使原始cookie是持久的).因此,因为您将validateInterval设置为0(始终验证每个请求),您实际上永远不会获得持久cookie.
| 归档时间: |
|
| 查看次数: |
5470 次 |
| 最近记录: |