How to protect static files with ASP.NET forms authentication in IIS 7.0 and 7.5
Posted: (EET/GMT+2)
Earlier this week, I was migrating an older ASP.NET application to Windows Server 2008 R2 with IIS 7.5 as the web server platform. The application was a pretty simple one: it basically shared a set of HTML documents with everybody who knew the password. The older platform was IIS 6.0 on Windows Server 2003.
During migration, I also wanted to improve the authentication of the site with traditional ASP.NET Forms authentication. However, by default, ASP.NET web applications only protect .ASPX files from being accessed, but not static content like HTML files and other such files.
How would you go and fix this problem? The easiest way is to add some module handling statements to your web application's web.config file. The following are the ones you need to add:
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
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>
If you look at this configuration, it first removes a module, and then adds it again. The modules removed and then re-added are FormsAuthenticationModule, UrlAuthorization and DefaultAuthentication modules. At first, this might look a little counter-intuitive: what does it help to first remove and then add the same module again?
This "magic" works because there is a pre-condition in the default modules that static files are not protected by Forms authentication. This is to keep IIS 7.x working in the same fashion as older IIS 6.0.
To boot, if you simply add the above configurations to your web.config, your web application will only serve static content to authenticated users. By using the regular ASP.NET authorization blocks in web.config under system.web section, you can suddenly limit accessing static content as well.
Note that this configuration only works with IIS 7.0 and 7.5 in the integrated pipeline mode. This pipeline mode is specified in the settings of the application pool that is configured to handle the web application in question.