ASP.NET Core 5 Web API 没有为方案“cookies”注册的登录身份验证处理程序

时间:2021-02-08 22:52:23

标签: c# asp.net-mvc asp.net-identity

我是 ASP.NET Identity 的新手,我的 ASP.NET Core 5 Web API 上有这个登录功能:

[HttpPost("login")]
public async Task<IActionResult> login([FromBody] LogIn logIn)
{
    var user = await _userManager.FindByEmailAsync(logIn.Email);
    if (user == null)
    {
        return NotFound("User Not Found!");
    }
    else if (user != null && await _userManager.CheckPasswordAsync(user, logIn.Password))
    {
        var claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
                //...
            }, "Cookies");

        var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
        await Request.HttpContext.SignInAsync("Cookies", claimsPrincipal);
        return Ok();

    }
    else
    {
        return BadRequest("Email and/or Password not valid!");
    }
}

但是当我登录时,我收到此错误:

<块引用>

System.InvalidOperationException: 没有登录身份验证处理程序 已为“Cookies”方案注册

我该如何解决这个问题?我将评论我的 setup.cs 文件,因为堆栈。

1 个答案:

答案 0 :(得分:0)

确保您configure you services correctly,您需要添加


Startup 类中,找到 ConfigureServices 方法并输入:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  .AddCookie(options =>
  { // all your options
    options.Cookie.HttpOnly = true;
    // in dev
    options.Cookie.SecurePolicy = _environment.IsDevelopment()
      ? CookieSecurePolicy.None : CookieSecurePolicy.Always;
      options.Cookie.SameSite = SameSiteMode.Lax;
  });

例如在新的 5.0

.AddCookie(config =>
        {
            config.Cookie.HttpOnly = true;
            //options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            config.Cookie.SameSite = SameSite.Lax;
            config.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;
            config.LoginPath = "/Login"; // your login path
        });

其他内容

<块引用>
  1. 清除缓存
  2. 开启HTTPS,在VS中找到该选项
  3. 关闭 GDPR,它现在可能包含在模板中,如果用户不接受,则不会设置 cookie。