How do I protect static files with ASP.NET form authentication on IIS 7.5?

Egil Hansen picture Egil Hansen · May 25, 2010 · Viewed 34.7k times · Source

I have a website running on a IIS 7.5 server with ASP.NET 4.0 on a shared host, but in full trust.

The site is a basic "file browser" that allows the visitors to login and have a list of files available to them displayed, and, obviously, download the files. The static files (mostly pdf files) are located in a sub folder on the site called data, e.g. http://example.com/data/...

The site uses ASP.NET form authentication.

My question is: How do I get the ASP.NET engine to handle the requests for the static files in the data folder, so that request for files are authenticated by ASP.NET, and users are not able to deep link to a file and grab files they are not allowed to have?

Best regards, Egil.

Answer

Joel Cunningham picture Joel Cunningham · May 25, 2010

If you application pool is running in Integrated mode then you can do the following.

Add the following to your top level web.config.

  <system.webServer>
    <modules>
      <add  name="FormsAuthenticationModule"  type="System.Web.Security.FormsAuthenticationModule" />
      <remove  name="UrlAuthorization" />
      <add  name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"  />
      <remove  name="DefaultAuthentication" />
      <add  name="DefaultAuthentication"  type="System.Web.Security.DefaultAuthenticationModule" />
    </modules>
  </system.webServer>

Now you can use the standard ASP.NET permissions in your web.config to force forms authentication for all files in the directory.

<system.web>
    <authorization>
        <deny users="?" />
    </authorization>
    <authentication mode="Forms" />
</system.web>