2017-09-18 53 views
5

我使用验证下面的代码在ASP.NET 2.0的核心使用cookie没有authenticationScheme指定,也没有发现DefaultChallengeScheme饼干认证

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”

的饼干设置如下:

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

我做了一些研究,但没有找到解决方案。这里是我使用的链接:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x

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

+1

可能重复[ASP.NET Core 2.0身份验证中间件](https://stackoverflow.com/questions/ 45805411/asp-net-core-2-0-authentication-middleware) –

回答

-1

HttpContext.Authentication是在ASP.net核心2.0过时的,所以不是 HttpContext.Authentication.SignInAsync使用HttpContext.SignInAsync

+0

确实如此,但与OP的问题无关。过时也并不意味着它不再有效。 – poke

+0

据我记忆,在这种变化之后,它开始为我工作。 – YuriyP

2
authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …) 

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

然而,在AddAuthentication电话,您使用的是不同的方案名称:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 

此注册CookieAuthenticationDefaults.AuthenticationScheme,它具有恒定值"Cookies",作为缺省的认证方案。但是这个名字的方案永远不会被注册!相反,只有一个"MyCookieMiddlewareInstance"

因此,解决方案是简单地为这两个调用使用相同的名称。您也可以使用默认值,并删除显式名称;如果你没有多种方案并需要更多的控制,那就没有必要明确地设置他们的名字。

0

对于那些谁降落在此留下沮丧,我的建议是看看在这个问题的答案:ASP.NET Core 2.0 authentication middleware

,而无需重新迭代,你发现有什么太大的话,看来这个问题是关系到ASP.Net Core 1和2之间的安全性变化。当然,那里的建议解决了我自己的问题。这也是值得看看这篇博客文章:https://ignas.me/tech/custom-authentication-asp-net-core-20/(我怀疑是基于这样的回答写的)

+0

虽然这个链接可能回答这个问题,但最好在这里包含答案的基本部分,并提供参考链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/18085439) –

+0

如果你的意思是这个链接的答案,那么这可能会活到只要SO做?我很乐意删除该博客文章的链接;它本质上是对第一个答案的重新考虑,所以它并没有真正增加太多。但它也可能没有害处。 –

+0

并非如此,如果该用户的SO内容发生变化,则该答案不再有效。通常情况下,您可以离开链接,但是如果链接内容发生更改,则会从链接中复制必要的部分,并留在此处。 –