Asp.Net 核心 - 在服务器 运行 时修改身份验证方案

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

有没有办法在服务器 运行 时 modify/add/remove 身份验证方案?

我需要在不 重新启动我的服务器的情况下添加方案

如果要更改服务器中运行的代码,则无法修改authentication schemes

除非您使用 Azure webapp,否则您可以创建一个插槽来热启动您的应用程序。

建议:

您需要更改您的代码,并重建您的项目,并且您必须重新启动您的 webapp。可以考虑动态添加认证方案

AuthSamples.DynamicSchemes

这个代码库应该对你有用。更多详情,可参考下方post.

Adding new authentication schemes dynamically

添加新方案的关键在于 IOptionsFactory<TOptions> 对象。

虽然您可以配置多个相同类型的 IAuthenticationHandler,但 authenticationScheme 字段指定每个配置(在源代码中称为 TOptions)。

因为所有运行时选项都在启动时配置和“密封”(参见:options in asp.net core)。不可能在运行时添加新选项(至少不编写一些代码)。

要添加新的身份验证方案,我们需要:

  1. 将新的 ConfigureNamedOptions<TOptions> 添加到 IOptionsFactory<TOptions>。这在初始化

    时为方案的IAuthenticationHandler提供了配置
  2. 将新方案添加到 IAuthenticationSchemeProvider。这会将 AuthenticationHandler 的实例绑定到步骤 1

    中提供的特定授权方案选项
  3. 清除 IOptionsMonitorCache<TOptions> 缓存 - 强制选项刷新

此代码添加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

在添加oidc2方案之前:oidc1可以访问身份服务器,而oidc2不能

以编程方式添加 oidc2 方案后 - oidc2 可以访问身份提供者