asp.net-mvc

How do I protect a file from direct download?


I have a webshop im developing, and some of the products need to be downloadable files (e-books, images, mp3 etc.). I have the files stored in a subfolder in my project and just a reference to them in my DB.

I dont want anyone with a direct file link to be able to download them, i want to control this myself. The download should only be available through my shop - that is, my customer area where the user can see all the e-products they have purchased.

How do i protect the files on my disk from being downloaded except by my code?


Solution

  • There are several ways to prevent the IIS static file handler from serving out the files to a client.

    1. Using <requestFiltering> section in configuration. You can use the hiddenSegments element to specify sub-segment paths that will not be served. Look at %windir%\system32\inetsrv\config\applicationhost.config for how this section is defined and used to prevent access to bin folder and other directories.

      <configuration>
          <system.webServer>
              <security>
                  <requestFiltering>
                      <hiddenSegments>
                          <add segment="subdirectoryName" />
                      </hiddenSegments>
                  </requestFiltering>
              </security>
          </system.webServer>
      </configuration>
      
    1. If you're looking for a simpler "poor-man's" way of blocking static file handler from serving out files, you can make the files "hidden" (from a file system attribute perspective). The static file handler will not serve out hidden files.