ASP.NET MVC 3 Simple Authorization Script for Static Files

Let's say I have a really simple site where I allow registered users to upload files. I have user "andrew" with identifier 1 and user "matte" with identifier 2.

Let's say I want to use the following folder structure to organize downloaded files.

/Content/DocRepo/[[ID]]/files_live_here 

I use forms authentication, so I can use the web configuration location element to prevent unauthorized users from accessing DocRepo, however after logging in to "andrew", which is the cleanest / easiest way to prevent it from accessing "matte" files ?

Could he just change the url to /Content/DocRepo/2/

+4
source share
2 answers

The easiest way to do this is to not allow direct file requests at all. Prevent requests from the file directory and instead create a file controller that requires Auth and ensures that the user has access to the file they request.

You can use the App_Data subdirectory to store files, since by default direct requests cannot be made for any files contained in it.

+7
source

This can be done in Global.asax under Application_AuthenticateRequest or Application_BeginRequest. You can also register IHTTPHandeler and follow the same logic as Global.asax, which will listen for requests to the DocRepo folder and audit user permissions.

If you use ASP.NET MVC, you can easily create a “Download” action on your controller, which takes some kind of file identifier and performs your check. If you are using classic ASP.NET, you will create a page, download.aspx, which accepts some unique identifier (as suggested by Andrew).

In MVC, you can add an authorization filter to an action to allow only authenticated users, and from there you can check the level of each user. In MVC there is a file result:

  return File(...); 
+2
source

Source: https://habr.com/ru/post/1391845/


All Articles