我正在构建一个ASP.Net Core 2 PoC,用于我们需要进行的一些身份验证/授权讨论/决策。
我目前正处于用户刚刚定义了此应用程序想要支持的新OpenID提供程序的位置。
支持此功能的一种方法是在启动期间读取所有已配置的提供程序,并在ConfigureServices
内配置它们。但是有一些诱人的线索,它们也可以做到这一点,而不必杀死并重新启动应用程序。
IAuthenticationSchemeProvider
有AddScheme
方法,看起来很理想。现在我需要做的就是构建一个AuthenticationScheme
对象,而我是金色的。它有一个构造函数AuthenticationScheme(string name, string displayName, Type handlerType)
但我不确定如何正确使用Microsoft.AspNetCore.Authentication.OpenIdConnect
中的类型来正确构造此对象,并允许我为此指定OpenID Connect特定选项。
我认为我想要用于第三个参数的类型是OpenIdConnectHandler
。但是我如何处理我的选择呢? (或者替代方案 - 我如何做到相当于能够提供Action<OpenIdConnectOptions>
代表)
我发现this github issue也是有意义的(没有TryAddScheme
方法,所以例外情况是可能的,如果我们选择进一步说服这个PoC,那么抽象有趣)但是小样本没有&#39}。谈谈选项。
答案 0 :(得分:6)
这里有一个如何执行此操作的示例 - https://github.com/aspnet/AuthSamples/tree/master/samples/DynamicSchemes
请记住,对于OAuth方案,您必须执行更多操作,然后只需调用schemeProvider.AddScheme和optionsCache.TryAdd - 在通过常规方法添加选项时,还会有一个“postconfigure”步骤。这是班级 - https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.OAuth/OAuthPostConfigureOptions.cs
因此,您可以注册“OAuthPostConfigureOptions&gt;”类型进入你的DI容器然后通过构造函数获取它并在选项上调用OAuthPostConfigureOptions.PostConfigure,然后将选项添加到optionsCache。
答案 1 :(得分:1)
除了上述https://stackoverflow.com/a/49825151/2200690中的schemeProvider.AddScheme和optionsCache.TryAdd之外,还要扩展上述答案(https://github.com/aspnet/AspNetCore/blob/release/2.2/src/Security/samples/DynamicSchemes/Controllers/AuthController.cs),我们需要在Startup.cs和AuthController.cs中进行进一步的更改:
在Startup.cs中
public void ConfigureServices(IServiceCollection services)
{
...
// register to the DI container so it can be injected in the AuthController constructor.
services.AddSingleton<OpenIdConnectPostConfigureOptions>();
...
}
在AuthController.cs中
在AuthController构造函数中注入OpenIdConnectPostConfigureOptions
:
public AuthController(IAuthenticationSchemeProvider schemeProvider,
IOptionsMonitorCache<OpenIdConnectOptions> optionsCache,
OpenIdConnectPostConfigureOptions postConfigureOptions)
{
_schemeProvider = schemeProvider;
_optionsCache = optionsCache;
_postConfigureOptions = postConfigureOptions;
}
在AuthController.cs的AddOrUpdate
方法中,创建OpenIdConnectOptions
类的实例,然后在后配置步骤中使用它:
var options = new OpenIdConnectOptions
{
Authority = "xxx-endpoint",
CallbackPath = "/signin-oidc",
ClientId = "XXX",
ClientSecret = "XXX",
......
};
_postConfigureOptions.PostConfigure("oidc", options);
_optionsCache.TryAdd("oidc", options);