在ASP.NET Core 5中,OpenIDConnect的配置可能会出现问题,使得默认/根路由无法正常工作。这是因为OpenIDConnect在添加Authentication Middleware时,会更改默认的路由:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}");
endpoints.MapRazorPages();
});
这里的问题在于,OpenIDConnect内部定义了一个“UseAuthentication” Extension方法,该方法将默认的authenticationScheme更改为OpenIDConnect的方案名称(“OpenIdConnectDefaults.AuthenticationScheme”),而RazorPages或ControllerRoute的Endpoint将使用此authenticationScheme。(通常在配置Auth的时候我们会在Add[认证]中添加authenticationScheme,但是如果不指定Scheme,他会默认使用系统的authenticationScheme) 如果您的应用依赖于默认路由,则需要在配置OpenIDConnect之前将Authentication Middleware添加到管道中:
app.UseRouting();
app.UseAuthentication(); //add this line before OpenIDConnect
app.UseAuthorization();
app.UseOpenIdConnectAuthentication(...);// your open id config here
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}/{id?}");
endpoints.MapRazorPages();
});
通过在OpenIDConnect之前添加Auth中间件,您可以确保应用程序的默认/根路由仍然会正常工作。