簡體   English   中英

沒有指定authenticationScheme,並且沒有找到DefaultChallengeScheme的Cookies身份驗證

[英]No authenticationScheme was specified, and there was no DefaultChallengeScheme found Cookies Authentication

我使用下面的代碼在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

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

我做了一些研究,沒有找到解決方案。 這是我使用的文檔的鏈接

任何人都可以讓我知道如何解決這個問題?

authenticationBuilder.AddCookie("MyCookieMiddlewareInstance", …)

這將使用身份驗證方案名稱"MyCookieMiddlewareInstance"注冊cookie身份驗證處理程序。 因此,無論何時提到cookie身份驗證方案,您都需要使用該確切名稱,否則您將找不到該方案。

但是,在AddAuthentication調用中,您使用的是另一個方案名稱:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

CookieAuthenticationDefaults.AuthenticationScheme具有常量值"Cookies"CookieAuthenticationDefaults.AuthenticationScheme注冊為默認身份驗證方案。 但具有該名稱的計划從未注冊過! 相反,只有"MyCookieMiddlewareInstance"

所以解決方案是簡單地為兩個調用使用相同的名稱。 您也可以只使用默認值,並刪除顯式名稱; 如果您沒有多個方案並需要更多控制,則無需明確設置其名稱。

對於那些落在這上面並且感到沮喪的人,我的建議是看看這個問題的答案: ASP.NET Core 2.0認證中間件

如果沒有重新迭代你發現的東西太多,似乎這個問題與ASP.Net Core 1和2之間的安全性變化有關。當然,那里的建議解決了我自己的問題。 這篇博客文章也值得一看: https//ignas.me/tech/custom-authentication-asp-net-core-20/ (我懷疑這是根據SO答案編寫的)

HttpContext.Authentication在ASP.net核心2.0中已經過時,因此HttpContext.Authentication.SignInAsync使用HttpContext.SignInAsync

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM