未指定authenticationScheme,并且未找到DefaultChallengeScheme Cookies身份validation

我使用下面的代码在ASP.NET Core 2.0中使用cookie进行身份validation

services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie("MyCookieMiddlewareInstance", options => { options.AccessDeniedPath = new PathString("/Account/Login"); options.LoginPath = new PathString("/Account/Login"); options.LogoutPath = new PathString("/Account/LogOff"); }); 

我收到一个错误:

未指定authenticationScheme,并且未找到DefaultChallengeScheme

Cookie设置如下:

 var claims = new List { new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim(ClaimTypes.Name, userName) }; var identity = new ClaimsIdentity(claims, "Forms"); identity.AddClaim(new Claim(ClaimTypes.Role, "ADMIN")); var principal = new ClaimsPrincipal(identity); HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal, new AuthenticationProperties { IsPersistent = isPersistent, ExpiresUtc = DateTime.UtcNow.AddYears(1) }); 

我做了一些研究,没有找到解决方案。 这是我使用的doc的链接 :

任何人都可以让我知道如何解决这个问题?

 authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …) 

这将使用身份validation方案名称"MyCookieMiddlewareInstance"注册cookie身份validation处理程序。 因此,无论何时提到cookie身份validation方案,您都需要使用该确切名称,否则您将找不到该方案。

但是,在AddAuthentication调用中,您使用的是另一个方案名称:

 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 

CookieAuthenticationDefaults.AuthenticationScheme具有常量值"Cookies"CookieAuthenticationDefaults.AuthenticationScheme注册为默认身份validation方案。 但具有该名称的计划从未注册过! 相反,只有一个"MyCookieMiddlewareInstance"

所以解决方案是简单地为两个调用使用相同的名称。 您也可以使用默认值,并删除显式名称; 如果您没有多个方案并且需要更多控制,则不需要明确设置其名称。

对于那些落在这上面并且感到沮丧的人,我的建议是看看这个问题的答案: ASP.NET Core 2.0认证中间件

如果没有重新迭代你发现的东西太多,似乎这个问题与ASP.Net Core 1和2之间的安全性变化有关。当然,那里的建议解决了我自己的问题。 这篇博客文章也值得一看: https : //ignas.me/tech/custom-authentication-asp-net-core-20/ (我怀疑这是根据SO答案编写的)

HttpContext.Authentication在ASP.net核心2.0中已经过时,所以改为HttpContext.Authentication.SignInAsync使用HttpContext.SignInAsync