【问题标题】:No authenticationScheme was specified, and there was no DefaultChallengeScheme found Cookies Authentication没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme Cookies Authentication
【发布时间】:2018-02-26 15:58:52
【问题描述】:

我正在使用以下代码在 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");
    });

我收到一个错误:

没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme

cookies 设置如下:

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)
});

我做了一些研究,但没有找到解决方案。这是我用过的a link to the doc

谁能告诉我如何解决这个问题?

【问题讨论】:

标签: c# authentication asp.net-core


【解决方案1】:
authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …)

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

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

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

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

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

【讨论】:

  • 对我来说只有默认的作品。更改这两个值会导致相同的错误。是否还有其他“隐藏”位置我也必须更改它。
  • 那么方案名和默认方案名都一样吗?您是否使用其他与身份验证相关的东西,例如身份?还是您只注册了一个身份验证方案?
  • 我认为它使用了 AddCookie 而没有提供任何方案。我的错!
【解决方案2】:

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

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

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • 如果您指的是 SO 答案的链接,那么它可能会与 SO 一样长吗?我很乐意删除博客文章的链接;它首先是对 SO 答案的重新迭代,所以它并没有真正增加太多。但它可能也没有坏处。
  • 并非如此,如果该分析器上的 SO 内容发生更改,则此答案不再有效。通常您可以留下链接,但如果链接将保留在这里,则复制链接中的重要部分内容变化。
  • 我真的不想这样做,因为我已将此问题标记为我引用的 SO 问题的可能重复项。我可以将那里的答案复制粘贴到我的答案中,但我认为将另一个答案(已经有更多分数)作为默认答案更有意义。
【解决方案3】:

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

【讨论】:

  • 是的,但与 OP 的问题无关。过时也不意味着它不再工作。
  • 据我所知,它在更改后开始为我工作。
猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 2021-10-18
  • 2019-03-22
  • 1970-01-01
  • 2019-08-02
  • 2021-05-24
  • 1970-01-01
  • 2021-10-11
相关资源
最近更新 更多