首页 > 解决方案 > 对来自多个来源(例如 Cognito 和 Azure)的令牌进行身份验证

问题描述

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

似乎添加超过 1 个提供程序会InvalidOperationException在应用程序启动时引发“方案已存在:承载”。

下面是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();
    });
}

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

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

标签: c#asp.net-coreauthenticationjwtazure-ad-b2c

解决方案


我们不能在相同的方案名称下注册 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");

和授权配置:

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

推荐阅读