gpt4 book ai didi

c# - 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme Cookies Authentication

转载 作者:IT王子 更新时间:2023-10-29 04:14:58 25 4
gpt4 key购买 nike

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

我收到一个错误:

No authenticationScheme was specified, and there was no DefaultChallengeScheme found

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

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

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

最佳答案

authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …)

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

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

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

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

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

关于c# - 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme Cookies Authentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46273789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com