在IServiceCollection扩展中访问IMemoryCache

时间:2019-07-11 11:32:00

标签: c# .net asp.net-core asp.net-web-api .net-core

我通过调用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;
}

能够做到这一点的好方法是什么?

1 个答案:

答案 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;
}