持久Cookie被删除浏览器关闭-身份2.0

本文关键字:身份 Cookie 删除 浏览器 持久 | 更新日期: 2023-09-27 18:11:18

我使用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);
    }
}

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;
}

private async Task<SignInStatus> SignIn(User user, bool isPersistent)
{
    await SignInAsync(user, isPersistent);
    return SignInStatus.Success;
}

public async Task SignInAsync(User user, bool isPersistent)
{
    var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
    AuthenticationManager.SignIn(
       new AuthenticationProperties
        {
           IsPersistent = isPersistent
        },
        userIdentity
    );
}

启动。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()))
       }
   });

对不起的代码墙,但我看不出我做错了什么,cookie不会持续3小时,当浏览器关闭而不手动注销?

持久Cookie被删除浏览器关闭-身份2.0

问题是OnValidateIdentity中的一个错误,当重新生成cookie时,当前总是将IsPersistent设置为false(即使原始cookie是持久的)。因此,由于将validateInterval设置为0(总是验证每个请求),因此实际上永远不会获得持久cookie。