在 ASP.NET Core 上配置 DefaultScheme 和 DefaultChallengeScheme 有什么意義?混合身份認證問題


我正在學習安全性如何在 ASP.NET Core 2.0 和 IdentityServer4 上工作。我使用 IdentityServer、API 和 ASP.NET Core MVC Client App 設置項目。

ConfigureService客戶端應用程序上的方法如下。在這里,我對DefaultScheme感到困惑DefaultChallengeScheme配置這些有什么意義?如果可能的話,詳細描述它是如何工作的會很有幫助。

我已經看到了DefaultScheme而不是DefaultSignInScheme也可以工作,但它是如何工作的?那些有什么區別?

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        //options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        //options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.SignInScheme = "Cookies";
        options.RequireHttpsMetadata = false;

        options.Authority = "http://localhost:5000/";
        options.ClientId = "mvcclient";
        options.SaveTokens = true;
    });
}

解答:

多個 AddAuthentication() 調用似乎是問題所在。請參閱https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-6.0

問題是這個。我試圖設置AddAuthentication兩次。

嗯,那行不通。AddAuthentication與其他Add~方法一樣,添加了使身份驗證工作所需的服務。因此,就其本身而言,多次調用它的效果為零。

但是,傳遞參數的時候,那么你配置AuthenticationOptions為好。

調用services.AddAuthentication(schemeName)基本相同,如下:

services.AddAuthentication(options =>
{
    options.DefaultScheme = schemeName;
});

因此,在您的情況下,您將默認方案配置為CookieAuthenticationDefaults.AuthenticationScheme但是當您再次調用AddAuthentication時,您正在重新配置選項。由於您同時設置了DefaultAuthenticateSchemeDefaultChallengeScheme,因此設置最終如下所示:

options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

正如我在另一個答案中詳細解釋的那樣,僅在未配置更明確的默認值時才使用默認方案。但是,每個身份驗證操作僅調用一個方案。

當您將身份驗證中間件與 一起使用時app.UseAuthentication()將使用默認的身份驗證方案來對用戶進行身份驗證。不過,在您的情況下,這是 JWT 承載方案,因此擁有 cookie 的用戶將不會通過身份驗證。只有當您刪除 的配置時DefaultAuthenticateSchemeDefaultScheme才會使用 來成功驗證用戶。

要解決您的問題,您應該決定默認情況下要使用的單一方案如果您的應用程序是具有 UI 的標准 Web 應用程序,那么您希望它成為 cookie 方案,以便訪問您的應用程序的用戶將得到正確的身份驗證。如果您另外有一些需要使用 JWT 承載來驗證客戶端的 API,那么您應該考慮在這些 API 上明確要求該方案。例如,您可以通過在授權策略中指定方案或使用[Authorize]屬性來做到這一點

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyApiController : ControllerBase
{
    …
}

 

來自:https://stackoverflow.com/questions/63403002/user-identity-isauthenticated-is-false-after-log-in-and-setting-cookies


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM