在ASP.net CORE 3框架中,要更新身份验证Cookie,可以使用以下代码:
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddDays(7) });
其中,CookieAuthenticationDefaults.AuthenticationScheme
是身份验证方案的名称,principal
是包含用户标识信息的ClaimsPrincipal
对象。
首先,使用SignOutAsync
方法注销当前用户的身份验证Cookie。然后,使用SignInAsync
方法重新创建并签署身份验证Cookie,并将其添加到响应中。在此处,我们传递一个IsPersistent
属性,以指示Cookie是否应该保持持久性,并且还可以设置过期时间。
完整的代码示例:
[HttpPost]
public async Task Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// authenticate user
var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
// create claims principal
var principal = await _claimsPrincipalFactory.CreateAsync(user);
// sign in user
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddDays(7) });
return RedirectToAction("Index", "Home");
}
}
// return error
ModelState.AddModelError("", "Invalid email or password");
return View(model);
}