当我编写我的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类
public class CustomUserStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>, IUserLoginStore<ApplicationUser>, IUserLockoutStore<ApplicationUser>, IUserPhoneNumberStore<ApplicationUser>, IUserTwoFactorStore<ApplicationUser>
CustomRoleStore类
public class CustomRoleStore : IRoleStore<ApplicationRole>
我现在需要实现记住我的功能,并且通过更改你期望工作的一个选项(密码到密码签名 - IsPersistent总是假的,现在它可以是真的),我的请求仍然返回认证使用auth cookie但后续请求返回401,因为他们无法获取auth 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 现在从永远变为假,有时变为真。
请提前帮助并提前感谢任何指示!