对来自多个来源(例如 Cognito 和 Azure)的令牌进行身份验证

Nin*_*ark 7 c# authentication jwt azure-ad-b2c asp.net-core

我们正在开发一种 API,它允许用户通过许多不同的提供商进行身份验证。单独的提供程序不是问题,但事实证明将它们一起使用是一个挑战。

InvalidOperationException当应用程序启动时,似乎添加 1 个以上的提供者会抛出“方案已经存在:承载”。

下面是ConfigureServices函数来自Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "Value";
            options.Audience = "Value";
        })
        .AddMicrosoftIdentityWebApi(options =>
        {
            Configuration.Bind("AzureAdB2C", options);

            options.TokenValidationParameters.NameClaimType = "name";
        },
        options => { Configuration.Bind("AzureAdB2C", options); });
    
    services.AddControllers();
    services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder(
            JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser()
            .Build();
    });
}
Run Code Online (Sandbox Code Playgroud)

我使用 Microsoft 示例对 Azure AD 进行身份验证作为起点。删除AddJwtBearerorAddMicrosoftIdentityWebApi调用工作正常,但我需要为我们的用例配置两个提供程序。

有没有办法在 .NET Core 3.1 或更高版本上做到这一点?

Rav*_*r B 6

我们不能在同一个方案名称下注册 2 个身份验证。所以我们需要用不同的名称注册 2 个身份验证方案(或者一个使用默认名称,另一个使用方案名称)在我的情况下,我正在注册 2 个身份验证方案:

  1. 我自己的 JWT 方案,我们的应用程序名称为“MyAppName”,
  2. 使用 JWT 默认方案的 Azure AD 身份验证JwtBearerDefaults.AuthenticationScheme,因为我无法使用自定义方案名称添加它。

我能够使用以下配置使其工作:

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer("MyAppName",options =>
            {
                 options.Authority = "Value";
                 options.Audience = "Value";                    
            })
            .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
Run Code Online (Sandbox Code Playgroud)

和授权配置:

        services.AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder(
                "MyAppName",
                JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser()
            .Build();
        });
Run Code Online (Sandbox Code Playgroud)