我正在尝试配置我的 Jwt Bearer 颁发者密钥,但在生产中,我通常使用由 KeyManager
包装的 Azure Key Vault.KeyManager
类是在依赖注入中配置的,但是在 ConfigureServices
方法中我不能使用它(显然),但是如果我不能使用它,我就无法检索我的密钥.
I am trying to configure my Jwt Bearer issuer key but, in production usually, I use Azure Key Vault wrapped by a KeyManager
.
The KeyManager
class is configured in Dependency Injection but, in ConfigureServices
method I cannot use that (obviously), but if I cannot use that I cannot retrieve my key.
我目前的解决方案是建立一个临时服务提供者并使用它,但我认为不是最先进的(我需要创建两个单例副本,不是最好的).
My solution at the moment is to build a temporary service provider and use it, but I think is not the state of the art (and I need to create two copies of singletons, not the best).
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;
});
使用 选项模式并实现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>();
这篇关于Jwt Bearer 和依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!