我正在尝试配置Jwt Bearer颁发者密钥,但是通常在生产中,我使用由KeyManager
包裹的Azure Key Vault。KeyManager
类是在依赖注入中配置的,但是,在ConfigureServices
方法中,我不能(显然)使用它,但是如果我不能使用它,则无法检索我的密钥。
目前,我的解决方案是建立一个临时服务提供商并使用它,但是我认为这不是最新的技术(我需要创建两个单例副本,而不是最好的)。
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;
});
因此,经过更多研究,我在Microsoft的文档上找到了此页面:Use DI services to configure options(也请参阅that answer,它涉及动态地处理多个Jwt颁发者)。
services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IKeyManager>((options, 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;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer();