在 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

原文地址:https://www.cnblogs.com/djd66/p/15660293.html