我使用以下代码在ASP.NET核心2.0认证使用cookies
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");
});
我得到一个错误:
未指定身份验证方案,并且未找到 DefaultChallengeScheme
饼干设置如下:
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)
});
我做了一些研究,但没有找到解决方案。这是我使用的文档的链接:
有人能告诉我如何解决这个问题吗?
authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …)
这将使用身份验证方案名称"MyCookieMiddleware Instance"
注册cookie身份验证处理程序。因此,每当您引用cookie身份验证方案时,您都需要使用该确切名称,否则您将找不到该方案。
但是,在AddAuthentication
调用中,您使用了不同的方案名称:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
这会将具有常量值“Cookie”
的 CookieAuthenticationDefaults.AuthenticationScheme
注册为默认身份验证方案。但是具有该名称的计划从未注册过!相反,只有一个“MyCookieMiddlewareInstance”。
因此,解决方案是简单地对两个调用使用相同的名称。您也可以只使用默认值,并删除显式名称;如果您没有多个方案,并且需要更多的控制,就没有必要显式地设置它们的名称。
对于那些登陆并沮丧离开的人,我的建议是看看这个问题的答案: ASP.NET Core 2.0 身份验证中间件
不用重复你在那里发现的太多,这个问题似乎与ASP.Net核心1和2之间的安全性变化有关。当然,那里的建议解决了我自己的问题。也值得看看这篇博客文章:https://ignas.me/tech/custom-authentication-asp-net-core-20/(我怀疑这是基于SO的答案写的)
HttpContext. Authentication
在ASP.net核心2.0中已过时,因此使用HttpContext.Authentic.SignInAsync
代替HttpContext.SignInAsync