Wednesday, December 8, 2010

PDFWebViewer.NET tip 1: protect your documents from direct access

Most of the PDFWebViewer.NET demos use the FileSystemStorageProvider to store PDF documents in the ~/documents folder. This means the documents are stored within the root of the website and they can be downloaded directly. If you know the file name, that is. To prevent direct access, you can either store the documents outside the web application root or setup some protective measures.

Protecting PDF documents in your site in IIS7
One of the easiest ways to protect your documents from direct access is to add the following web.config file to the root of the PDF storage area (i.e. ~/documents in the demo applications):

<?xml version="1.0"?>
<configuration>
   <!-- Prevent direct access to all files in this folder -->
   <system.web>
      <httphandlers>
         <add type="System.Web.HttpNotFoundHandler" verb="*" path="*" />
      </httphandlers>
   </system.web>

   <system.webserver>
      <validation validateintegratedmodeconfiguration="false" />

      <handlers>
         <remove name="BlockViewHandler" />
         <add name="BlockViewHandler" type="System.Web.HttpNotFoundHandler" verb="*" path="*" precondition="integratedMode" />
      </handlers>
   </system.webserver>
</configuration>

This file is based on the web.config file used to protect the ~/Views folder in ASP.NET MVC applications. The general idea is that all direct requests for url’s within the storage area are handled by the HttpNotFoundHandler. In effect this generates a 404 response, so that it seems like the requested file is not found even though it is on disk.

Protecting PDF documents in IIS7 Classic Mode
If you are running IIS7 in classic mode, you’ll have to do some additional configuration in IIS to make sure .pdf files are handled by ASP.NET and not served by IIS directly as static content.

In the IIS7 administration console, select your site and open the ‘Handler Mappings’. Click ‘Add Script Map…’ from the links on the right side. Fill in the dialog like show below. The exact path for the executable can be copied from the handler mappings that have already been defined.

image

1 comment:

gullbyrd said...

httphandlers should be httpHandlers