Static file authorization in ASP.NET Core MVC

When we want to serve static file ins ASP.NET Core, we should have to read this document.

Let’s imagine serving some static protected files with authorization. These files are only accessible by authorized users.

Configure Authorization

It’s required to configure authorization, but it’s independent of configuring static file authorization. You can configure authorization with your favorite way. Please read the document. Here is a sample.

Locate protected files

In the above code, files under wwwroot folder can be publicly accessible as I call UseStaticFiles method. We should have to locate protected files the folder except for wwwroot folder. I create www folder and locate a file.

Serve static files with authorization

We don’t have to configure service for this www folder like UseStaticFilesmethod. If we configure www folder for static file middleware by calling UseStaticFiles method, files under www folder can be publicly accessible. Please note all files are publicly accessible when we use Static File middleware. We only have to return FileResult in the controller action.

We should have to return PhysicalFileResult by specifying an absolute file path. Then we can serve banner1.svg file with authorization.

Originally published at tech.en.tanaka733.net on January 9, 2017.