-->

Prevent direct access to files on IIS server

2020-07-18 20:27发布

问题:

I have two servers, one for my mvc application and the other one as a storage for large files like images etc, both running on Windows Server 2012 R2.

How can I prevent direct access to the files on storage server?

say, mvc is on IP1/ and storage is on IP2/.

Link to a file would be like: IP2/MediaFiles/2015/12/image0001.jpg.

I need only GET requests from IP1 have access to the link above. How?


UPDATE

server1 on IP1 needs to be free of file sharing since media server is on IP2 and we don't need to load files per request on server1's RAM. (server1 will crash soon!) therefore no HttpHandler can be used!

In this question I'm looking for a way to prevent unauthorized users from accessing files on server2 (on IP2) by entering direct address.

回答1:

Alright I found the solution!

Working on such problems needs some trick gathered from different sources based on your needs. I was looking for a way to prevent unauthorized users from accessing files on file server which is different from your main server. (the main server is authorizing users)

First of all, I blocked ALL incoming requests containing the Url pattern of my sensitive files using IIS rules. Then I wrote some lines of code for file server to handle Http requests using IHttpHandler interface in order to 1) check authorization rules and 2) send exact files to clients without converting them to byte array. And lastly, I used This Link to prettify links to file server! That's all folks ;)

Now:

physical link [blocked] : IP2/MediaFiles/2015/12/image0001.jpg

virtual link : IP2/Please/Find/A/File/By/DB/Id/1 ---> image0001.jpg



回答2:

All what you wanted is in Web.Config file. You should place it in the root directory of your file storage server if you using IIS there.

In <system.webServer> node you should place this code:

<security>
    <ipSecurity allowUnlisted="false">    <!-- this line blocks everybody, except those listed below -->                
        <clear/> <!-- removes all upstream restrictions -->
        <add ipAddress="127.0.0.1" allowed="true"/>    <!-- allow requests from the local machine -->
        <add ipAddress="IP1" allowed="true"/>   <!-- allow the specific IP of IP1  -->                             
    </ipSecurity>
</security>

This rule will be accepted for all subfolders of root folder. If you need to block requests only for specific folder you should place your Web.Config threre.

Theck this article if you wanted to know more about IP black and white lists in IIS.