gpt4 book ai didi

c# - JwtBearerOptions 配置方法未执行

转载 作者:行者123 更新时间:2023-12-02 01:44:16 30 4
gpt4 key购买 nike

我有 asp.net core 3.1 Web api 项目,代码如下:

Startup.cs

public virtual void ConfigureServices(IServiceCollection services) =>
services
.AddFrameworkServices()
.AddApplicationInsights(this.configuration)
.AddResponseCompression()
.AddCustomConfigureOptions();

CustomServiceCollectionExtensions.cs

public static IServiceCollection AddCustomConfigureOptions(this IServiceCollection services) =>
services
.ConfigureOptions<ConfigureAuthenticationOptions>();
.ConfigureOptions<ConfigureJwtBearerOptions>();

ConfigureAuthenticationOptions.cs

public class ConfigureAuthenticationOptions : IConfigureOptions<AuthenticationOptions>
{
public void Configure(AuthenticationOptions options) =>
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}

配置JwtBearerOptions

public class ConfigureJwtBearerOptions : IConfigureOptions<JwtBearerOptions>
{
private readonly IConfiguration configuration;
public ConfigureJwtBearerOptions(IConfiguration configuration) => this.configuration = configuration;
public void Configure(JwtBearerOptions options)
{
options.Authority = configuration[C.AppKeys.AADInstance] + configuration[C.AppKeys.AADTenantID];
options.Audience = configuration[C.AppKeys.AADAudience];
}
}

在调试时我发现ConfigureJwtBearerOptions.cs文件的Configure方法没有被触发

任何人都可以帮助我指导解决此问题

最佳答案

我正在使用 .Net Core 6 并遇到同样的错误。这里的巧妙之处在于 .AddJwtBearer() 使用命名选项委托(delegate)。

不要实现 IConfigureOptions,而是实现 IConfigureNamedOptions

配置JwtBearerOptions.cs

public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
{
private readonly JwtOptions config;
private readonly ILogger<ConfigureJwtBearerOptions> logger;

/// <summary>
/// Configure JWT auth
/// </summary>
/// <param name="jwtOptions"></param>
/// <param name="logger"></param>
public ConfigureJwtBearerOptions(JwtOptions jwtOptions, ILogger<ConfigureJwtBearerOptions> logger)
{
config = jwtOptions;
this.logger = logger;
}

/// <inheritdoc/>
public void Configure(JwtBearerOptions options)
{
Configure(JwtBearerDefaults.AuthenticationScheme, options);
}

public void Configure(string name, JwtBearerOptions options)
{
options.Authority = config.Authority;
options.Audience = config.Audience;

logger.LogInformation("OAuth authority: {0}", config.Authority);
logger.LogInformation("OAuth audience: {0}", config.Audience);
//...
}
}

此外,您还需要在 Startup.cs 中调用 AddAuthentication()

Startup.cs

//...
services.AddAuthentication().AddJwtBearer();

关于c# - JwtBearerOptions 配置方法未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71132926/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com