为什么“ UseAuthentication”必须放在“ UseRouting”之后而不是之前?

问题描述 投票:0回答:1

根据documentation,中间件的顺序应如下所示:

app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

我有基于this article的中间件来保护静态文件(保护某些路由)。我遇到的问题是该订单对我不起作用。如果用户已经被授权,我只能保护一个文件夹。所以我需要将UseProtectFolder放在UseStaticFiles之前以及UseAuthenticationUseAuthorization之后:

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseProtectFolder(new ProtectFolderOptions
{
    Path = "/Secret",
    PolicyName = "Authenticated"
});
app.UseStaticFiles();

但是不会返回任何静态文件。似乎UseRouting正在做一些使文件不可用的操作,返回404,因为当我将顺序更改为UseRouting之后将UseStaticFiles移到该位置时,它会起作用:

app.UseAuthentication();
app.UseAuthorization();

app.UseProtectFolder(new ProtectFolderOptions
{
    Path = "/Secret",
    PolicyName = "Authenticated"
});
app.UseStaticFiles();

app.UseRouting();

因此,实际的更改顺序是将UseAuthentication放在UseRouting之前(甚至是UseStaticFiles之前。

从文档中:

中间件组件在Startup.Configure方法定义中间件的顺序组件是根据请求和相反的顺序调用的响应。该顺序对于安全性,性能和功能

我的问题现在是:为什么按照记录的顺序,UseAuthentication放在UseRouting之后?

是有特定原因还是仅出于性能方面的原因?通过在管道中更早地移动身份验证/授权,这是否会影响响应(逆序)?

asp.net-core asp.net-core-3.0 asp.net-core-middleware
1个回答
0
投票

发布此问题后,我在github上打开了一些有关本地化的问题,希望获得更多信息。尽管不是所有问题都得到直接回答,但它帮助我找到了这个问题的答案。

阅读了大卫·福勒的评论后:

UseAuthorization()->将查看填充的用户和当前用户端点以确定是否需要应用授权策略。

我发现UseAuthorization没有问题。它用于端点,因此不需要它来保护文件夹。这也解释了为什么此语句仅在UseEndpoints语句之后才有意义。

为了完整了解我的配置,我有一个策略提供程序(包括策略),一个URL重写程序(如UseDefaultFiles)和用于保护某些文件夹的中间件。

我的结论是,我可以使用以下顺序,该顺序几乎与记录的顺序相同:

// Identify the user. The only statement that is not in the order as documented
app.UseAuthentication();

// Middleware that adds policies
app.UsePolicyProvider();
// Protect the folder by policy
app.UseProtectFolder(new ProtectFolderOptions { Path = "/p", PolicyName = "admin" });
// URL rewriter for serving tenant specific files
app.UseTenantStaticFiles();

// Serve the static files
app.UseStaticFiles();

app.UseCookiePolicy();
app.UseCors();

app.UseRouting();
app.UseRequestLocalization();
app.UseAuthorization();
app.UseEndpoints();

关于顺序的两点评论:

  1. UseRequestLocalization仅在UseRouting之后可用
  2. 涉及URL重写程序(如UseDefaultFiles)时,在UseRouting之后,UseStaticFiles不起作用。
© www.soinside.com 2019 - 2024. All rights reserved.