当我编写我的asp.net核心身份验证时,它不需要“记住我”功能,这就是我实现我的身份验证(滑动过期30分钟):

Startup.cs

var roleStore = new CustomRoleStore();
var userPrincipalFactory = new CustomUserPrincipalFactory();

services.AddSingleton<IRoleStore<ApplicationRole>>(roleStore);
services.AddSingleton<IUserClaimsPrincipalFactory<ApplicationUser>>(userPrincipalFactory);

services.AddIdentity<ApplicationUser, ApplicationRole>(options => {
    options.Cookies.ApplicationCookie.ExpireTimeSpan = 30;
    options.Cookies.ApplicationCookie.SlidingExpiration = true;
}).AddDefaultTokenProviders();

AccountController.cs

[HttpPost("Login")]
[AllowAnonymous]
public async Task<IActionResult> Login(UserLogin model)
{
    // If the model is valid, then attempt a login.
    if (ModelState.IsValid)
    {
        try
        {
            // Wait for the result for sign in.
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

            // If the call was successful, then update the last sign in.
            if (result.Succeeded)
                return Json(new { success = true, errorcode = 0, result = true });
        }
        catch (Exception ex)
        {
             return Json(new { success = false, errorcode = 115 });            
        }
    }

    // Return bad request response.
    return BadRequest(new { success = false, errorcode = 111 });
}

其他说明,我已经实现了自己的自定义用户存储和角色存储,其签名如下所示:

CustomUserStore class

public class CustomUserStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>, IUserLoginStore<ApplicationUser>, IUserLockoutStore<ApplicationUser>,  IUserPhoneNumberStore<ApplicationUser>, IUserTwoFactorStore<ApplicationUser>

CustomRoleStore class

public class CustomRoleStore : IRoleStore<ApplicationRole>

我现在需要实现记住我的功能,并且通过更改你期望工作的一个选项(密码到PasswordSignInAsync - IsPersistent始终是假的,现在它可以是真的),我的请求仍然返回身份验证以及身份验证cookie,但随后的请求返回401,因为他们无法获取身份验证cookie? (HttpContext.User.Identity.IsAuthenticated为false) . 我见过这样的文章:

How do I forcefully propagate role changes to users with ASP.NET Identity 2.0.1?

但他们似乎以与我相比略有不同的方式进行身份验证(我已经实现了自己的中间件来处理身份验证):

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(15),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
    },
    SlidingExpiration = false,
    ExpireTimeSpan = TimeSpan.FromMinutes(30)
});

任何人都可以建议如何让持久cookie工作?我可以换掉我的代码(在顶部)代码(在上面)吗?与此无效的唯一区别是,一个参数IsPersistent现在从永远变为虚假变为有时变为真 .

请提前帮助并感谢任何指示!