Monday, 15 January 2007

ASP.NET Sitemap and Role management

The asp.net 2.0 navigation system is a bit of confusion and the setup of the navigation is tricky. I spent several hours to make it work properly.

When we have a Menu control in a page and want the menu to display menu items based on the login user's role, we need to configure several places. There are several components in a navigation system: Membership, Role, SiteMap xml file such as web.sitemap, SiteMap datasource, web.config and Menu control. All these components work together to build a dynamic, user role aware navigation system.

Let's describe how to configure these components.

The membership and role modules are easy to configure, we can enable and configure them through the built in ASP.NET Configuration tool.

In the Web.sitemap file, we define the structure of the site.

 

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode url="" title="Top" description="" roles="*">
<siteMapNode url="GeneralUser.aspx" title="General User" description="" roles="GeneralUser" />
<siteMapNode url="PowerUser.aspx" title="Power User" description="" roles="PowerUser" />
</siteMapNode>
</siteMap>



The siteMapNode element has an attribute "roles", which defines what roles have the access to this item in a navigation control.

In the Web.config file, we define the site access in section:

 


<location path="GeneralUser.aspx">
<system.web>
<authorization>
<allow roles="GeneralUser"/>
<deny users="*" />
</authorization>
</system.web>
</location>

<location path="PowerUser.aspx">
<system.web>
<authorization>
<allow roles="PowerUser"/>
<deny users="*" />
</authorization>
</system.web>
</location>



The sections in Web.config define the actual access right for each page to roles.

The above two files should match with roles to make the navigation system work properly.

The Menu control and SiteMapDataSource control are easy to configure. In the web page which needs a menu (normally in a master page), just drag a SiteMapDataSource onto the page. Then drag a Menu control onto the page, set the DataSourceID property to the site map data source.

After all these are done, the whole site navigation system should be working properly.