According to the documentation, the order of middleware should be like this:
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
I have middleware to protect static files, based on this article (protecting certain routes). The problem I encounter is that the order doesn't work for me. I can only protect a folder if the user is already authorized. So I need to place UseProtectFolder before UseStaticFiles and after UseAuthentication and UseAuthorization:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseProtectFolder(new ProtectFolderOptions
{
Path = "/Secret",
PolicyName = "Authenticated"
});
app.UseStaticFiles();
But this will not return any static file. It looks like UseRouting is doing something that makes the file unavailable, returns 404, because when I change the order to this, moved UseRouting after UseStaticFiles, it works:
app.UseAuthentication();
app.UseAuthorization();
app.UseProtectFolder(new ProtectFolderOptions
{
Path = "/Secret",
PolicyName = "Authenticated"
});
app.UseStaticFiles();
app.UseRouting();
So the actual change in order is that UseAuthentication is placed before UseRouting (and even before UseStaticFiles).
From the documentation:
The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.
My question is now: in the order as documented, why is UseAuthentication placed after UseRouting?
Is there a particular reason or is it for performance reasons only? And by moving the authentication/authorization earlier in the pipeline, does this affect the response (reverse order)?
