c# - HttpContext SignInAsync 因 Cookie 和声明而失败
问题描述
我有一个 ASP.NET CORE 应用程序,我尝试添加一个使用 Cookie 进行身份验证的登录。
我有以下代码
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("CookieAuth")
.AddCookie("CookieAuth", config =>
{
config.Cookie.Name = "GroupHome.Cookie";
config.LoginPath = "/Account/SignIn";
});
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
...
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
...
登录.cs
public IActionResult Login(LoginModel lm)
{
using (var ctx = new GroupHomeContext())
{
try {
var user = ctx.Logins.SingleOrDefault(er => er.UserName == lm.UserName);
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)
{
HttpContext.SignInAsync(userPrincipal); <----- ERROR IS HERE
return RedirectToAction("/Dashboard/Employees");
}
return RedirectToAction("/Account/SignIn");
}
return RedirectToAction("/Account/SignIn");
}
catch (Exception ex)
{
return RedirectToAction("/Account/SignIn");
}
}
}
当用户登录时,所有数据库验证过程都可以,但是当我尝试将 ClaimsPrincipal 设置为 HttpContext.SignInAsync() 时,会出现以下错误。
解决方案
您正在调用异步方法SignInAsync,我想您也应该等待它并使方法async。
推荐阅读
- ruby-on-rails - Ruby on Rails 不同页面上的多个更新表单
- javascript - 将 jest 与 tensorflow.js 一起使用会产生错误
- windows-10-universal - Xamarin Form - 如何在 uwp 桌面应用程序中打开文档
- python-3.x - 使用 awsretry 模块时没有名为 syslog 的模块(未找到模块错误)
- python - 如何将数组上采样到任意大小?
- azure - 从 docker hub 删除 docker 镜像
- visual-studio-code - 如何在 Visual Studio Code 中自动化“在行尾添加分号并转到下一行”?
- angular - Wijmo 中的错误断言失败:预期日期
- angular - 在NGXS中组合多个@Select
- python - 删除行首的 \n