DuendeSoftware / Samples

Samples for our Products
Other
229 stars 269 forks source link

Dynamic Providers with OIDC Events #190

Open josephdecock opened 4 months ago

josephdecock commented 4 months ago

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 commented 4 months ago

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