我通过调用IMemoryCache
中的services.AddMemoryCache()
注册了Startup.cs
我想做的是能够在添加JWT身份验证的IServiceCollection
扩展方法中使用它。令牌的签名密钥存储在Azure Keyvault中,我想在检索密钥时对其进行缓存
public static IServiceCollection AddJWTAuth(this IServiceCollection services)
{
services.AddAuthentication(options=>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
jwt .TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tokenValidationParameters) =>
{
// Get signing from KV and add it to memory cache
// Use signing key from cache
}
};
});
return services;
}
能够做到这一点的好方法是什么?
答案 0 :(得分:1)
当您需要访问服务集合中已存在的内容时,可以使用BuildServiceProvider()
,这将为您提供到目前为止已配置的服务的服务提供商。请注意,必须在AddJWTAuth
方法之前添加内存缓存。
public static IServiceCollection AddJWTAuth(this IServiceCollection services)
{
var cache = services.BuildServiceProvider().GetRequiredService<IMemoryCache>()
services.AddAuthentication(options=>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt =>
{
jwt .TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tokenValidationParameters) =>
{
cache..GetOrCreate(...);
}
};
});
return services;
}