reggaemahn
reggaemahn

Reputation: 6668

Access IMemoryCache in IServiceCollection extension

I have registered IMemoryCache by calling services.AddMemoryCache() in my Startup.cs

What I want to do do is to be able to use this in an IServiceCollection extension method where I add JWT Authentication. The signing key for the token is stored in Azure Keyvault and I'd like to cache the key when I retrieve it

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

What's a good way of being able to do this?

Upvotes: 0

Views: 589

Answers (1)

wertzui
wertzui

Reputation: 5740

When you need to access what is already inside your service collection, you can use BuildServiceProvider() which will give you a service provider with the so far configured services. Note that you must add your memory cache before your AddJWTAuth method.

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

Upvotes: 1

Related Questions