問題描述
我正在嘗試配置我的 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模板網!