2

My core 2.0 app is set up with authentication roles, and I have my controller actions set with [Authorize(Roles="demo_user")] etc.

Authorization is working just fine, my question is how to lock down content directories and only serve them through a controller action?

Reading some docs, it looks like I need to serve docs based on this article: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files

And I believe the information I'm interested in is this paragraph:

Static file authorization The static file module provides no authorization checks. Any files served by it, including those under wwwroot are publicly available. To serve files based on authorization: Store them outside of wwwroot and any directory accessible to the static file middleware and Serve them through a controller action, returning a FileResult where authorization is applied

Does anyone have examples of storing directories outside of wwwroot and serving them via controller actions?

R. StackUser
  • 2,005
  • 4
  • 17
  • 24
  • 1
    You can see in [this answer](https://stackoverflow.com/a/42460443/19046) how to return a file from a controller. Then is up to you how to associate your route params with your files. – DaniCE Sep 20 '17 at 16:15
  • You can add a folder for your private files and add a condition to the middleware in startup.cs (app.Use) and check for request path.. if the path contained the private folder you can redirect the response – Armin Torkashvand Nov 28 '18 at 15:56

1 Answers1

1

To serve a file from an action in ASP.NET Core, you can do something like this:

[Authorize]
public IActionResult GetMyFile()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes("MyPrivateFiles/file1.txt");
    return new FileContentResult(fileBytes, "text/plain");
}

Keep in mind your application will need to have read permissions on the MyPrivateFiles folder.

Neil
  • 1,613
  • 1
  • 16
  • 18
  • Are there any examples with reading and returning complete directories? If I add additional content files to a specific directory, I don't want to have to hard code it into the controller. – R. StackUser Sep 20 '17 at 16:20
  • You could add a parameter to your action to return a file with a specific name, and create a separate action which returns a list of all files. Your .NET Core application can make use of the file system like any other app, but you have to create the interface to the file system in your controller with whatever features you want. – Neil Sep 20 '17 at 17:29
  • Here's documentation about this: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.1&tabs=aspnetcore2x#static-file-authorization – jaycer Jun 12 '18 at 19:32