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

标签 c# asp.net-core middleware

我正在将 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 Core 中中间件的概念,如果存在 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 Controller 的原因是静态文件中间件找到了所请求的文件,并选择不调用链中的下一个中间件。它只是返回文件作为响应。

身份验证中间件中的

AutomaticAuthenticate 始终意味着“检查传入请求。如果您发现感兴趣的内容,请从中创建一个 ClaimsPrincipal”。在这种情况下,当登录用户的登录 cookie 位于请求中时,cookie 身份验证会自动为登录用户创建主体,然后再将请求传递给下一个中间件。

OpenId Connect 中间件实际上会执行,但它不会执行任何操作,因为即使它具有 AutomaticAuthenticate = true,它也不会在请求中找到任何有趣的内容。它正在寻找对其回调路径的请求,该路径默认设置为 constructor 中的 CallbackPath = new PathString("/signin-oidc"); .

两个身份验证中间件的设置如下,以便 cookie 中间件始终运行,但 OpenId Connect 仅在请求时重定向到身份提供者(例如,通过从 MVC Controller 返回 ChallengeResult)。

关于c# - ASP.NET Core 中的中间件是如何执行的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42393194/

相关文章:

c# - 包含只读项目的 ReadOnlyCollection

c# - 引发事件的模式

c# - SVG - 获取两条路径的差异路径

asp.net-core - 延迟加载在 EntityFramework Core 中不起作用

http - 如何使用中间件惯用地记录身份验证信息

c# - 如何确保用户在 aspnet core 2.0 中完成他们的个人资料?

c# - 欺骗应用程序关于鼠标位置的信息

c# - .net core 版本冲突

c# - 带有 url-formencoded 的模型属性自定义名称

javascript - 将请求参数传递到使用 'createHandler' 的 'graphql-http' 函数的中间件