Saturday, April 19, 2008

ASP NET: How to secure a web page in a sub directory using role for your web site?

In ASP.NET 2.0, we can use the built-in role-based security feature to control who can access certain directories within our web site. It's quite straight forward to setup some configurations in the Web.config file that define the roles that can access a direcotry. For example,


1 <location path="MemberDirectory">
2 <system.web>
3 <authorization>
4 <allow roles="MEMBER" />
5 </authorization>
6 </system.web>
7 </location>



But to control the role that can access a specific file in a sub-directory within our site requires us to set it differently. The following example shows how it can be done:


1 <location path="Admin/UserManagement">
2 <system.web>
3 <authorization>
4 <deny users="*" />
5 </authorization>
6 </system.web>
7 </location>
8
9 <location path="Admin/UserManagement/users.aspx">
10 <system.web>
11 <authorization>
12 <allow roles="ADMIN" />
13 <deny users="*" />
14 </authorization>
15 </system.web>
16 </location>


The 1st line shows the setting to deny all users to access the particular sub-directory.
The 9th line shows the setting to allow access to individual web page for the ADMIN role.
In order for any page in the UserManagement sub-directory to be shown in a MS ASP web menu, you need to include all the individual pages in the setting.