【问题标题】:Access IMemoryCache in IServiceCollection extension在 IServiceCollection 扩展中访问 IMemoryCache
【发布时间】:2019-07-11 11:32:00
【问题描述】:

我已通过在我的Startup.cs 中调用services.AddMemoryCache() 注册IMemoryCache

我想做的是能够在我添加 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;
}

有什么好的方法可以做到这一点?

【问题讨论】:

  • 更明确地说明您要做什么。
  • @Nkosi 我已经添加了详细信息

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


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多