How to control access to specific directories in ASP.NET

A usual application design is to place files that require authentication into a separate folder.  You can follow this approach in ASP.NET by leaving the <authorization> element in the normal parent directory empty and adding a web.config file that specifies stricter settings in the secured directory.

When you add the web.config file in the subdirectory it should contain only the authorization information, as shown. You cannot change the <authentication> tag settings in the web.config file of a subdirectory in your application. As an alternative, all the directories in the application have to use the same authentication system. On the other hand, each directory can have its own authorization rules.




<deny users=”?” />





When you are using authorization rules in a subdirectory, ASP.NET still reads the authorization rules from the parent directory. The difference is that it applies the rules in the subdirectory first and ASP.NET stops as soon as it matches an authorization rule.


If for example the root virtual directory contains this rule


<allow users=”mike” />


and subdirectory contains this rule:


<deny users=”mike” />



the user mike  will access any resource in the root directory but no resources in the subdirectory. If you reverse these two rules, mike will access resources in the subdirectory but not the root directory.

ASP.NET allows allows an unlimited hierarchy of subdirectories and authorization rules. You can have a a virtual directory with authorization rules, a subdirectory that defines additional rules, and then a subdirectory inside that subdirectory that applies even more rules. In this case you should imagine all the rules as a single list, starting with the directory where the requested page is located. If all those rules are processed without a match, ASP.NET then begins reading the authorization rules in the parent directory, and then its parent directory, and so on, until it finds a match. If no authorization rules match, ASP.NET will ultimately match the <allow users=”*”> rule in the  machine.config file.