如何在调用函数 AddJwtBearer(jwtBearerScheme, o => { }) 后设置 JwtBearerOptions;在 asp.net 核心中有空选项?

How to set JwtBearerOptions after calling function AddJwtBearer(jwtBearerScheme, o => { }); with empty opts in asp.net core?

我正在使用 Asp.net Core 3.1。在使用 Visual Studio 创建新的 Web 项目时,我们使用 select API 模板并将身份验证更改为 Individual User Accounts 并配置 Azure ADB2C 选项,最后创建项目。

在我们生成的 Startup.cs 文件中,我们有以下函数:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
        .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
    services.AddControllers();
}

可以找到 AddAzureADB2CBearer() 的实现 here。这个实现有一行代码如下:

builder.Services.Configure(scheme, configureOptions);
    builder.AddJwtBearer(jwtBearerScheme, o => { });

在上面的行中,它添加了 JwtBearer 和空 JwtBearerOptions。并且身份验证工作完美。但是我想在下面这行代码之后设置一些JwtBearerOptions

services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

执行以上两行后,有没有办法配置这些选项?我尝试了以下几行,但没有任何效果。

services.Configure<JwtBearerOptions>(options =>
{
     options.TokenValidationParameters.ValidateIssuer = false; // accept several tenants (here simplified)
     options.Events = new JwtBearerEvents
     {
         OnAuthenticationFailed = AuthenticationFailed
     };

     options.TokenValidationParameters = new TokenValidationParameters()
     {
          ValidateLifetime = true,
          ValidateAudience = true,
          ValidAudience = "myAudience"
      };
});

请注意,我可以使用 AddJwtBearer 函数并在设置后传递选项。但我想使用 Microsoft 默认实现。并且只需要更新作为参数传递给 AddJwtBearerJwtBearerOptions

您可以尝试覆盖AddAzureADB2CBearer之后的特定模式:

services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
    .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

services.Configure<JwtBearerOptions>(AzureADB2CDefaults.JwtBearerAuthenticationScheme, options =>
{
    options.TokenValidationParameters.ValidateIssuer = false; // accept several tenants (here simplified)
    options.Events = new JwtBearerEvents
    {
        OnAuthenticationFailed = AuthenticationFailed
    };

    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateLifetime = true,
        ValidateAudience = true,
        ValidAudience = "myAudience"
    };
});