【问题标题】:Authenticating tokens from multiple sources (e.g Cognito and Azure)对来自多个来源(例如 Cognito 和 Azure)的令牌进行身份验证
【发布时间】:2021-03-01 22:46:06
【问题描述】:

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

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

下面是来自Startup.csConfigureServices函数

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 示例 for authenticating with Azure AD 作为起点。删除 AddJwtBearerAddMicrosoftIdentityWebApi 调用工作正常,但我需要为我们的用例配置这两个提供程序。

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

【问题讨论】:

  • 这个错误是有道理的,看起来内部方案Bearer 被两个提供商使用。我认为他们可能有一些选择来改变方案,如果没有的话,你需要编写自己的提供者来结合这两个提供者。这就是解决这个问题的逻辑,但实际上我以前从未做过类似的事情。
  • 您找到解决方法了吗?我也在寻找解决方案
  • 不,还没有。对于我们的解决方案,我们已经做出让步,即在应用程序的生命周期内只使用其中一种,因为我们通常不会在任何生产场景中混合和匹配。也就是说,可能可以剖析AddJwtBearer 调用并指定不同的方案,以免它与AddMicrosoftIdentityWebApi 调用中使用的Bearer 方案发生冲突。如果我有空闲时间,我会尝试举一个例子作为答案:)

标签: c# asp.net-core authentication jwt azure-ad-b2c


【解决方案1】:

我们不能在同一个方案名称下注册 2 个身份验证。所以我们需要注册两个不同名字的认证方案(或者一个是默认的,另一个是方案名) 就我而言,我正在注册 2 个身份验证方案:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2011-06-29
    • 2018-10-04
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多