Samples icon indicating copy to clipboard operation
Samples copied to clipboard

Dynamic Providers with OIDC Events

Open josephdecock opened this issue 1 year ago • 1 comments

We use the OIDC handler's events for lots of advanced functionality (JWT authentication, JAR, PAR, etc). It would be good to add a sample to show how to do so for dynamic providers.

josephdecock avatar May 23 '24 19:05 josephdecock

Some beginnings:

public class ConfigureDynamicProviders(IHttpContextAccessor httpContextAccessor) 
    : IPostConfigureOptions<OpenIdConnectOptions>
{
    public void PostConfigure(string? name, OpenIdConnectOptions options)
    {
        ArgumentNullException.ThrowIfNull(name, nameof(name));
        if(httpContextAccessor.HttpContext is null)
        {
            throw new InvalidOperationException("No Http Context (are you accidentally trying to configure providers in a background service?)");
        }

        // We have to resolve the cache this way because of scoping
        var cache = httpContextAccessor.HttpContext.RequestServices.GetRequiredService<DynamicAuthenticationSchemeCache>();

        var provider = cache.GetIdentityProvider<OidcProvider>(name);
        if(provider != null)
        {
            provider.Properties.TryGetValue("custom", out var custom);

            // Instantiate an Events object that will do the authentication work you like
            // options.Events = new PrivateKeyJwtOidcEvents(name, custom)
        }
        else
        {
            // The cache will miss for any statically configured OIDC providers (if you have a mix of static and dynamic)
        }
    }
}

josephdecock avatar May 23 '24 19:05 josephdecock