ASP.NET Core使用Cookie和Claims调用HttpContext.SignInAsync失败
核心错误原因
HttpContext.SignInAsync是异步方法,你当前以同步方式直接调用未加await,请求上下文会在身份校验写入Cookie的操作完成前就被释放,导致调用异常- 你注册的Cookie认证方案名为
CookieAuth,调用SignInAsync时未显式指定方案名,可能出现方案不匹配问题
修复步骤
- 将Login方法改为异步签名,返回
Task<IActionResult>,调用SignInAsync时添加await关键字,同时显式传入你注册的认证方案名CookieAuth - 补充空值校验逻辑,避免用户不存在时抛出空引用异常
修复后Login方法代码示例
// 引入必备命名空间 using Microsoft.AspNetCore.Authentication; using System.Threading.Tasks; public async Task<IActionResult> Login(LoginModel lm) { using (var ctx = new GroupHomeContext()) { try { var user = ctx.Logins.SingleOrDefault(er => er.UserName == lm.UserName); // 补充用户为空的校验逻辑 if (user == null) { return RedirectToAction("/Account/SignIn"); } if (Decrypt(user.Password) == lm.Password) { var employee = ctx.Employees.SingleOrDefault(em => em.EmployeeId == user.EmployeeId); var employeeRole = ctx.EmployeeToRoles.SingleOrDefault(er => er.EmployeeId == employee.EmployeeId); var Role = ctx.Roles.SingleOrDefault(rl => rl.RoleId == employeeRole.RoleId); var GroupHomeClaims = new List<Claim>() { new Claim(ClaimTypes.NameIdentifier, employee.EmployeeId.ToString()), new Claim(ClaimTypes.Email, employee.Email), new Claim(ClaimTypes.Role, employeeRole.RoleId.ToString()) }; var GroupHomeIdentity = new ClaimsIdentity(GroupHomeClaims, "Group Home Identity"); var userPrincipal = new ClaimsPrincipal(new[] { GroupHomeIdentity }); if (userPrincipal != null) { // 增加await关键字+显式指定注册的认证方案名 await HttpContext.SignInAsync("CookieAuth", userPrincipal); return RedirectToAction("/Dashboard/Employees"); } return RedirectToAction("/Account/SignIn"); } return RedirectToAction("/Account/SignIn"); } catch (Exception ex) { return RedirectToAction("/Account/SignIn"); } } }
额外检查项
你当前Startup.cs里的中间件顺序是正确的,UseAuthentication放在UseAuthorization之前符合要求,无需调整。只需要确认项目已经安装了Microsoft.AspNetCore.Authentication.Cookies NuGet包即可。
内容的提问来源于stack exchange,提问作者Carlos Andrés Montoya Cardona
相关产品推荐
相关产品推荐

