ASP.NET Core 中的中间件是如何执行的

How are middlewares executed in ASP.NET Core

我正在将 Auth0 添加到简单项目并尝试了解中间件的工作原理。

在我的 Startup.cs 我有这个代码

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<AuthSettings> auth0Settings)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
       app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();

    // Add the cookie middleware
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true
    });

    // Add the OIDC middleware
    var options = new OpenIdConnectOptions("Auth0")
    {
        // here there are some configurations
        // .....................
    };

    options.Scope.Clear();
    options.Scope.Add("openid");
    options.Scope.Add("name");
    options.Scope.Add("email");
    options.Scope.Add("picture");

    app.UseOpenIdConnectAuthentication(options);

    app.UseMvc(routeBuilder =>
    {
       routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}");
    });
}

如果我正确理解ASP.NET核心中的中间件的想法在我们的示例中,如果存在cookie并且可以通过它进行身份验证

 app.UseCookieAuthentication(new CookieAuthenticationOptions
 {
      AutomaticAuthenticate = true,
      AutomaticChallenge = true
 });

不会执行OpenId中间件。

 app.UseOpenIdConnectAuthentication(options);

有人可以解释一下 OpenId 中间件是如何知道它不应该被执行的吗?

在底部我们有

app.UseMvc(routeBuilder =>
{
     routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}");
});

它怎么知道它应该始终被执行,但是在我们请求一些静态文件的情况下我们不使用 mvc。

管道中的每个中间件都可以选择调用下一个中间件。您获取静态文件而不是它命中 MVC 控制器的原因是静态文件中间件找到请求的文件,并选择不调用链中的下一个中间件。它只是 returns 文件作为响应。

AutomaticAuthenticate 在身份验证中间件中始终意味着 "Inspect the incoming request. If you find something that interests you, create a ClaimsPrincipal from it." 在这种情况下,cookie 身份验证会在请求中包含登录 cookie 时自动为登录用户创建主体,然后再传递请求到下一个中​​间件。

OpenId Connect 中间件实际执行,但它不执行任何操作,因为它不会在请求中找到任何有趣的内容,即使它有 AutomaticAuthenticate = true。它正在寻找对其回调路径的请求,默认情况下在 constructor.

中设置为 CallbackPath = new PathString("/signin-oidc");

两个身份验证中间件是这样设置的,因此 cookie 中间件始终运行,但 OpenId Connect 仅在请求时重定向到身份提供者(例如,通过从您的 MVC 控制器返回 ChallengeResult)。