gpt4 book ai didi

c# - Jwt Bearer 和依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-04 00:57:35 25 4
gpt4 key购买 nike

我正在尝试配置我的 Jwt Bearer 颁发者 key ,但通常在生产中,我使用由 KeyManager 包装的 Azure Key Vault .KeyManager类在依赖注入(inject)中配置,但在 ConfigureServices方法我不能使用它(显然),但是如果我不能使用它,我就无法检索我的 key 。

我目前的解决方案是建立一个临时服务提供者并使用它,但我认为不是最先进的(我需要创建两个单例副本,不是最好的)。

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
ServiceProvider sp = services.BuildServiceProvider();
IKeyManager keyManager = sp.GetService<KeyManager>();

options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = keyManager.GetSecurityKeyFromName("jwt").Result,

ValidIssuer = "https://api.example.com",
ValidateIssuer = true
};

options.Audience = "https://api.example.com";
options.Authority = "https://api.example.com";

options.SaveToken = true;
});

最佳答案

使用Options pattern并实现IConfigureNamedOptions<JwtBearerOptions> :

public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
{
private readonly IKeyManager _keyManager;

public ConfigureJwtBearerOptions(IKeyManager keyManager)
{
_keyManager = keyManager;
}

public void Configure(JwtBearerOptions options)
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = _keyManager.GetSecurityKeyFromName("jwt").Result,

ValidIssuer = "https://api.example.com",
ValidateIssuer = true
};

options.Audience = "https://api.example.com";
options.Authority = "https://api.example.com";

options.SaveToken = true;
}

public void Configure(string name, JwtBearerOptions options)
{
Configure(options);
}
}

在 Startup.cs 中:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer();

services.ConfigureOptions<ConfigureJwtBearerOptions>();

关于c# - Jwt Bearer 和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186836/

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