Asp.Net Core - modify authentication schemes while server is running

Viewed 435

Is there a way to modify/add/remove authentication schemes while the server is running?

I need to add scheme without restarting my server.

2 Answers

The key for adding new scheme resides withing the IOptionsFactory<TOptions> object.

While you may configure multiple IAuthenticationHandler's of same type the authenticationScheme fields specifies each's configuration (in source code it is referred as TOptions).

As all runtime options are configured and "sealed" at startup (see: options in asp.net core). It is not possible to add new option at runtime (at least without writing some code).

To add new authentication scheme we need to:

  1. Add new ConfigureNamedOptions<TOptions> to the IOptionsFactory<TOptions>. This provides the configuration to the scheme's IAuthenticationHandler when it is initialized

  2. Add new scheme to IAuthenticationSchemeProvider. This binds an instance of AuthenticationHandler to the specific authorization scheme options provided in step 1

  3. Clear IOptionsMonitorCache<TOptions> cache - Forces options refresh

This code adds OpenIdConnectHandler

//adds oidc2 scheme
var toAdd = new AuthenticationScheme("oidc2", "oidc2- display", typeof(OpenIdConnectHandler));
if (!_authenticationSchemeProvider.TryAddScheme(toAdd))
    return false;
var a = new Action<OpenIdConnectOptions>(options =>
{
    //configuration goes here
    options.Authority = "https://demo.identityserver.io/";
    options.ClientId = "c-id2";
});
_factory.AddOption("oidc2", a);
//clear cache
var allSchemes = await _authenticationSchemeProvider.GetAllSchemesAsync();
var services = Request.HttpContext.RequestServices;
var c = services.GetService<IOptionsMonitorCache<OpenIdConnectOptions>>();
foreach (var s in allSchemes)
    c.TryRemove(s.Name);

Click here to see source code on github

before adding oidc2 scheme: oidc1 can access the identity server while oidc2 cannot enter image description here

enter image description here

After adding oidc2 scheme programmatically - oidc2 can access identity provider enter image description here

If you want change the code which is running in your server, it's impossible to modify authentication schemes.

Unless you use Azure webapp, you can create a slot to hot start your application.

Suggestion:

You need change your code, and rebuild your project, and you must retsart your webapp. You can think about how to add authentication schemes dynamically.

AuthSamples.DynamicSchemes

This repo should be useful to you. For more details, you can refer below post.

Adding new authentication schemes dynamically

Related