没有指定authenticationScheme,并且没有找到DefaultChallengeScheme的Cookies身份验证

San*_*isy 30 c# authentication asp.net-core

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

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");
    });
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

未指定authenticationScheme,并且未找到DefaultChallengeScheme

Cookie设置如下:

var claims = new List<Claim>
{
    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)
});
Run Code Online (Sandbox Code Playgroud)

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

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

pok*_*oke 13

authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …)
Run Code Online (Sandbox Code Playgroud)

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

但是,在AddAuthentication通话中,您使用的是不同的方案名称:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
Run Code Online (Sandbox Code Playgroud)

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

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


Joh*_*lly 5

对于那些对此感到沮丧的人,我的建议是看看这个问题的答案:ASP.NET Core 2.0 authentication middleware

无需重复您在那里发现的内容,似乎这个问题与 ASP.Net Core 1 和 2 之间的安全性变化有关。当然,那里的建议解决了我自己的问题。还值得一看这篇博客文章:https : //ignas.me/tech/custom-authentication-asp-net-core-20/(我怀疑它是基于那个 SO 答案编写的)


Yur*_*iyP -1

HttpContext.Authentication在 ASP.net core 2.0 中已过时,因此请 HttpContext.Authentication.SignInAsync使用HttpContext.SignInAsync