Search code examples
c#asp.net-coreasp.net-core-staticfile

How do I serve static files only to authorized users?


I have a collection of Excel spreadsheets that I'd like to serve in my ASP.NET 5 webapp only to authorized users.

  1. Where should I store the files? I assume in wwwroot (e.g., wwwroot/files).
  2. If in wwwroot, how do I allow access only to authorized users? (I'd like to serve them up as a [Authorize] FileResult from the controller, but this still leaves the files open to direct access through a URL I believe.)
  3. How do I reference a location in wwwroot through my FileResult action in the controller?

Thanks much!


Solution

  • Yes, they should go in wwwroot. Currently there is no built-in way to secure wwwroot directories. But creating a middleware module to accomplish it is pretty straightforward. There is an easy to follow tutorial here.

    If you're not familiar with developing middleware, I posted a GitHub project that shows how to create middleware in three easy steps. You can download the project here.

    You don't need a controller to access static files.