根据documentation,中间件的顺序应如下所示:
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
我有基于this article的中间件来保护静态文件(保护某些路由)。我遇到的问题是该订单对我不起作用。如果用户已经被授权,我只能保护一个文件夹。所以我需要将UseProtectFolder
放在UseStaticFiles
之前以及UseAuthentication
和UseAuthorization
之后:
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
之后?
是有特定原因还是仅出于性能方面的原因?通过在管道中更早地移动身份验证/授权,这是否会影响响应(逆序)?
发布此问题后,我在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();
关于顺序的两点评论: