ASP.NET Menu and SiteMap Security Trimming (plus a trick for when your menu and security don't match up)


ASP.NET 2005 introduced a pretty solid menu which is integrated with a configuration driven sitemap. The cool part is that the menu can be hooked in with your security roles, so you don't have to worry about hiding or showing menu options based on the user - the menu options are automatically kept in sync with what the user is allowed to see. We'll talk about how to set this up, using an example from a website I worked on recently.

If you're familiar with ASP.NET sitemaps and menus, skip to the end to read a trick for working around cases when you want to do something more complex, such as have a page to be accessible to a user role, but not to show up in the menu.

The Video.Show site was originally planned to have only one class of user, with no user restrictions other than requiring a quick registration before commenting on videos or uploading videos. With that being the case, we just included a static menu in the masterpage, defined as <asp:MenuItem> elements. As we were gearing up for the first beta release, it became obvious that our user model was too simple. Hosted installations would probably want to allow users to register and begin commenting right away, not give all these users upload rights. That implied four classes of user now: unauthenticated, commenter, uploader, and also administrator (implied by the requirement to manage multiple user classes). That meant role management and new menu items to be kept in sync - the right time to move to a sitemap driven menu with security trimming.

Step One - Define The Sitemap

I'm using a static sitemap defined in a Web.sitemap file, and it's especially simple since there's no is no hierarchy involved. This uses the default XmlSiteMapProvider; there are other sitemap providers available on the internets, such as a SQL Sitemap Provider for database driven site structure, or you can implement your provider if you've got a custom situation.

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="" >
  <siteMapNode roles="*">
    <siteMapNode title="Home" url="~/Default.aspx" />
    <siteMapNode title="Videos" url="~/Tags.aspx" />
    <siteMapNode title="Members" url="~/MemberList.aspx" />
    <siteMapNode title="My Page" url="~/MyPage.aspx" />
    <siteMapNode title="My Recent Views" url="~/RecentViews.aspx" />
    <siteMapNode title="Upload a Video" url="~/Upload.aspx" />
    <siteMapNode title="Administer Users" url="~/AdministerUsers.aspx" />

Note that the IntelliSense for a .sitemap file is misleading:

Sitemap Intellisense

While the XSD for .sitemap files (from which the IntelliSense is derived) includes "securityTrimmingEnabled" attribute, it's incorrect. It's the result of an old VS 2005 bug that's still around. That value should be set in web.config; we'll take care of that next.

Step Two - Declare The Sitemap in web.config

A few things to notice here:

  • I define the provider type as System.Web.XmlSiteMapProvider
  • I specify the siteMapFile as the Web.sitemap file we've just discussed
  • I set securityTrimmingEnabled="true"
<siteMap enabled="true">
    <add siteMapFile="Web.sitemap" name="AspNetXmlSiteMapProvider" type="System.Web.XmlSiteMapProvider" securityTrimmingEnabled="true"/>
This is really just overriding the default sitemap settings from %windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config, which also uses the name AspNetXmlSiteMapProvider, but which doesn't include security trimming.

Step Three - Set required roles for the pages

This section of the web.config looks long, but you'll see it very repetitive. MSDN's information on setting up authorization rules is pretty well written, so take a look there if you'd like more info. The high points:

  • Rules are processed top to bottom. For example in the Upload.aspx case, a user in the Uploader role is allowed right off the bat, everyone else is denied.
  • Pages which are displayed to all authenticated users just need to deny unauthenticated users, like this: <deny users=?">
  • There's no wildcard for roles, so you can't say something like <allow roles="*">.
  • Role based permissions is configured by default in machine.config (using both AspNetSqlRoleProvider and AspNetWindowsTokenRoleProvider). The Sql Role Provider assumes a database connectionstring named LocalSqlServer, so if your profile information is stored somewhere else you'll need to make sure the rolemanager is configured correctly.
<location path="Upload.aspx">
      <allow roles="Uploader"/>
      <deny users="*" />
<location path="Profile.aspx">
      <deny users="?" />
<location path="MyPage.aspx">
      <deny users="?" />
<location path="RecentViews.aspx">
      <deny users="?" />
<location path="AdministerUsers.aspx">
      <allow roles="Administrator"/>
      <deny users="*"/>

Step Four - Add A Sitemap Data Source and a Menu to your Master Page

<asp:SiteMapDataSource runat="server" ID="siteMapDataSource" ShowStartingNode="false" />
<asp:Menu runat="server" ID="MainMenu" Orientation="Horizontal" DataSourceID="siteMapDataSource" />
You'll probably want to style the menu, too. I'm a fan of the CSS Friendly Control Adapters, which changes the HTML output to use clean UL. Without the Control Adapter, the Menu control outputs nested tables manipulated by JavaScript. Here's what the above menu looks like for a user who's logged in but isn't in the Administrator or Uploader roles:
 Video.Show Menu

The Payoff - Everything is Managed In One Place

That may seem like a lot to configure, and you might be wondering if it isn't easier to just write write your own code to handle access and menu management.

First off, the above actually goes pretty quickly - hopefully this post or others I've linked to make it a little faster.

Secondly, the real payoff is that you've now got a reliable, maintainable solution to controlling page access, and it's all automatically kept in sync. Let's say we want to add a new page that's only visible to users with Uploader rights - maybe a page (MyVideos.aspx) where they can edit or delete videos they've previously uploaded. I'd only need to add one page to the sitemap file, set the access rule in web.config to allow Uploaders and deny everyone else, and the page will only show up in the menu when an Uploader has logged in. This is a good application of the Don't Repeat Yourself philosophy. We don't have one set of logic determining what pages users are allowed to view and another set which determines what pages they should see in the menu; these are both the same list and should be handled that way.

Tip - Use a Url Mapping to alias pages when your access and menu visibility are more complex

I wanted to point out one other tip that came in handy here. Before we realized the need for different user types, we had one page called Member.aspx, which served two purposes. If the querystring contained some other user's userid, it would show their public profile and a list of their videos. We also repurposed it as My Page, determined by navigating to the page as a logged in user without using a querystring.

When we hooked up the menu and page access, we had a problem. We only wanted to show My Page in the menu when a user was logged in, but we needed the Member.aspx page to be viewable by anonymous users, because it was used for public user profiles, too. The simple solution was to set up a Url Mapping which created a virtual MyPage.aspx (mapped to Member.aspx). Now we could set different access rights to MyPage.aspx and Member.aspx, as shown in the Step Three code sample - Member.aspx is public, and MyPage.aspx requires authentication. Here's how the Url Mapping was set up:

  <add url="~/MyPage.aspx" mappedUrl="~/Member.aspx"/>


  • Good stuff and nice trick!

    My main project is on 1.1, but the security/sitemap system we created allows a very similar maneuver.

    What security mechanism do you use for actions controlling CRUD as well as special permissions on pages?

  • Cool trick!
    I just know it's a bug.

  • There's no context for the samples provided.
    e.g. if i were to add the location nodes to my web.config, where do i do this? Why force me to go and look for the information on another site when you could have specified this in one line of text? The same goes for the other configuration elements mentioned here. Otherwise, thanks for the info about the bug.

  • The Video.Show site was originally planned to have only one class of user, with no user restrictions other than requiring a quick registration before commenting on videos or uploading videos. With that being the case, we just included a static menu in the masterpage, defined as elements. As we were gearing up for the first beta release, it became obvious that our user model was too simple. Hosted installations would probably want to allow users to register and begin commenting right away, not give all these users upload rights. That implied four classes of user now: unauthenticated, commenter, uploader, and also administrator (implied by the requirement to manage multiple user classes). That meant role management and new menu items to be kept in sync - the right time to move to a sitemap driven menu with security trimming.

  • Hi Jon,

    In the middle of a similar problem where css adapters may help. I notice that when I run:

    choose Members, it leaves Members nicely highlighted. Once I choose a member to look at, I lose the context. That is, neither Home, Videos or Members remains highlighted.

    My problem is I have two rows of nav. Primary row is category, secondary row is details of that category. I always want to keep primary highlighed and secondary when person goes in.

    If you have an ideas, feel free to post. Hopefully, I'll figure it out and post on my blog. This is all about the new code camp site. Did I mention that? Silicon Valley Code Camp is 11/8-9. :)

  • Hi, where abouts in the Web.Config do you put the location nodes? Thanks

  • //This fixed everything for me in the StaticSiteMapProvider

    public override bool IsAccessibleToUser(HttpContext context, SiteMapNode node)

    foreach (string role in node.Roles)
    if (context.User.IsInRole(role))
    return true;
    return false;
    //return base.IsAccessibleToUser(context, node); //seems to always return true;

  • how to add a url with multiple querystring values in sitemap file in .net2.0

    Thanks & Regards
    Rajesh Yadav

  • You have a link to a non-existent page that is part of this explanation, labelled
    "make sure the rolemanager is configured correctly."

  • I'm trying to get my blog running on MySQL but the problem is that it is taking it long time trying to load the page but nothing happens !!!
    one more thing I have modified at the connection string which is the provider I used MySql provider instead of MSSQL
    any clue why am I getting the strange behavior ?

  • This is a wonderful post, very clear and well-written. I was able to implement this right away.

  • Big thx for this step-by-step tutorial. I am facing a problem that my menu is not updated (nodes shown/hidden)correctly when i switch the role while i am on a page used in location path in web.config.

    It gets only updated when i click the menu a second time, or reload the page.

    When i switch the role while i am on a site not mentioned in the webconfig (allowed to be accessed by every user) and i switch my role the menu gets updated correctly.

    Anybody else faced the problem?

  • This solution is not working for second level of folders. It works correctly only for pages in root folder, tried many solutions but no progress.

  • I've sorted problem of nested folders not working correctly basically it cannot take "~/" and the folder name needs to be like this:

    AND NOT like


  • Why You Are Not Giving A Demo Code !!!

  • Hi,

    I am currently using ADFS authentication mechanism to authenticate the user. In that case I am setting authenticationmode as None instead of forms authentication. After the user loggedIn successfully the claims object will provide the role data associated with the loggedIn user so in that case how the sitemap roles attribute will be able to pick up the role from the claims object. Can you explain me how the securityTrimmingEnabled property will be used.

    I used the custom class ADFSRoleProvider.cs which inherits the RoleProvider class and overridden the method GetRolesForUser method but the method is not invoked unless I am setting the

    and this in turn is also not able to interact with the roles attribute mentioned in the siteMapNode node.

    The main issue is after the user logins in successfully using the ADFS authentication mechanism how will the sitemap role attribute know about the role of the loggedIn User.

    Could please provide some code sample and help regarding the above mentioned issue.

    Thanks & Regards,
    Santosh Kumar Patro

  • hello... I am using membership,menu,sitemap

  • naturally like your website but you have to check the spelling on several of your posts.

    Several of them are rife with spelling problems and I find it
    very bothersome to inform the reality then again I'll definitely come again again.

  • I am not sure where you are getting your information,
    but great topic. I needs to spend some time learning much more or understanding more.
    Thanks for great info I was looking for this information for my mission.

  • My family all the time say that I am killing my time here at net, except I know I am getting experience
    every day by reading thes nice content.

  • Thanks in support of sharing such a pleasant thought, article is fastidious, thats why
    i have read it entirely

  • I am new to developing web sites and I was wanting to know if having your website title relevant to your articles and other content really that crucial?
    I see your title, " ASP.NET Menu and SiteMap Security Trimming (plus a trick for when your menu and security don't match up) " does seem to be spot on with
    what your website is about however, I prefer to
    keep my title less content descriptive and based more around site branding.

    Would you think this is a good idea or bad idea?
    Any assistance would be greatly appreciated.

  • Hello there just happened upon your website via Google after I typed in, " ASP.NET Menu and SiteMap Security Trimming (plus a trick for when your menu and security don't match up)" or perhaps something similar (can't quite remember exactly). Anyways, I'm glad I found it simply because your content is exactly
    what I'm searching for (writing a college paper) and I hope you don't mind if I collect some material from here and I will of course credit you as
    the source. Thanks for your time.

  • Hello there! Would you mind if I share your blog with my facebook group?
    There's a lot of people that I think would really enjoy your content. Please let me know. Thanks

  • pukgs

  • I was sent here from the Perez Hilton website

  • Having read this I believed it was very informative.
    I appreciate you finding the time and effort to put this short article together.
    I once again find myself personally spending a lot
    of time both reading and commenting. But so what, it was still worthwhile!

  • It's the best time to make some plans for the future and it is time to be happy. I've read this post and if I
    may I want to recommend you some attention-grabbing issues or advice.
    Perhaps you can write subsequent articles regarding this article.
    I desire to read more things about it!

  • This is the right site for anyone who really wants to find
    out about this topic. You understand so much its almost tough to argue with you
    (not that I actually would want to…HaHa). You certainly put a brand new
    spin on a topic that's been written about for years. Excellent stuff, just excellent!

  • I believe this is one of the so much vital information for
    me. And i am happy studying your article. However wanna observation on few common issues, The web site
    taste is great, the articles is in reality great : D.

    Just right job, cheers

  • Hi i am kavin, its my first occasion to commenting anywhere, when i read this post i thought i could also make comment due to this good paragraph.

  • TwellaJep

  • I was recommended this blog by my cousin. I'm not sure whether this post is written by him as no one else know such detailed about my problem. You're amazing!


  • I hunger for to compliment Obama on his success!

  • I every time used to study paragraph in news papers but
    now as I am a user of web so from now I am using net for
    articles or reviews, thanks to web.

  • Hello, i think that i noticed you visited my web site
    so i came to return the desire?.I'm trying to in finding things to improve my site!I suppose its ok to make use of a few of your ideas!!

  • I was wondering if you ever thought of changing the structure of your website?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could
    connect with it better. Youve got an awful lot of text for
    only having one or 2 images. Maybe you could
    space it out better?Watch The Good Wife Season 4 Episode 9 Online

  • If some one wants expert view on the topic of running a blog then i propose him/her to pay a visit this weblog, Keep up
    the nice work.

  • What a data of un-ambiguity and preserveness of precious knowledge on the topic of unexpected emotions.

  • Good post. I'm dealing with a few of these issues as well..

  • I usually do not create a comment, but I read a bunch of remarks on ASP.
    NET Menu and SiteMap Security Trimming (plus a trick for when your menu
    and security don't match up) - Jon Galloway. I actually do have 2 questions for you if it's allright.
    Is it just me or does it give the impression like
    a few of these comments look as if they are coming from brain dead folks?
    :-P And, if you are writing at other social sites, I would like to follow anything fresh you have
    to post. Would you make a list of all of your social networking pages like your linkedin profile, Facebook page or
    twitter feed?

  • Hey there would you mind letting me know which webhost you're utilizing? I've loaded your blog in 3 completely different web browsers and I must say
    this blog loads a lot faster then most. Can you recommend a good internet hosting provider at a fair price?
    Thanks, I appreciate it!

  • Thanks to my father who told me about this web site,
    this website is genuinely amazing.

  • you're in reality a good webmaster. The website loading pace is amazing. It seems that you're doing any distinctive trick.
    Moreover, The contents are masterwork. you have done a fantastic activity on this subject!

  • If you become aware that you have a ringworm infection, find a reputable ringworm cream and begin treatment as soon as possible to keep the infection from getting more severe.

  • I'd have to ensure with you here. Which is not a touch I customarily do! I have evaluation a post that will achieve nation ponder. As well, merit for allowing me to comment!

  • I really like what you guys are up too. This type
    of clever work and reporting! Keep up the good works guys Ive added you guys to our blogroll.

  • It's hard to find well-informed people in this particular topic, but you sound like you know what you're talking about!

  • Aw, this was an exceptionally good post. Finding the time and actual effort to generate a superb article… but what
    can I say… I hesitate a lot and don't manage to get nearly anything done.

  • Fantastic site. Lots of helpful info here. I'm sending it to several friends ans additionally sharing in delicious. And certainly, thanks for your sweat!Visit our polish website at Okna drewniane

  • Thanks for finally talking about >ASP.NET Menu and SiteMap Security Trimming
    (plus a trick for when your menu and security don't match up) - Jon Galloway <Loved it!

  • First of all I would like to say awesome blog!
    I had a quick question which I'd like to ask if you don't
    mind. I was interested to know how you center yourself and clear your thoughts prior to writing.
    I've had difficulty clearing my thoughts in getting my thoughts out there. I do take pleasure in writing however it just seems like the first 10 to 15 minutes are usually lost just trying to figure out how to begin. Any ideas or tips? Thanks!

  • With havin so much content and articles do
    you ever run into any problems of plagorism or copyright violation?
    My site has a lot of completely unique content I've either created myself or outsourced but it appears a lot of it is popping it up all over the internet without my permission. Do you know any methods to help protect against content from being stolen? I'd genuinely appreciate it.

  • Cheap VPS or virtual private server is the ultimate solution to costly maintenance web servers. In fact, virtual private server is more advanced than shared hosting & is more like dedicated server, but to emphasize, at a much lower cost. The low cost of virtual private server is the significant difference between shared web-site hosting and dedicated server. A slightly advanced than shared website hosting and has the features of a dedicated server, but it is way cheaper than a dedicated server. The financial advantage of using virtual private server is not the only advantage it could give to its customers or users. Explained below are the additional advantages and disadvantages of using cheap virtual private servers.

    Advantages of Cheap VPS:
    The first thing that you could get from your individual virtual private server is the root access to your server. It means that you can have access to the root level of the hosting server. Thus, you have the ability to put in & configure any programs you require. Additionally, you can also host a limitless number of net sites through Apache's virtual hosts & manage them efficiently. Not only this, but you can also host other services, such as a mail server, an FTP server, or any type of server you want. You may even use VPS for file storage or as a backup for all of your files. Since VPS is isolated from other sites present on the physical server, it is secured that no harmful script or application used by other webmaster, that can harm your website.

    Disadvantages of Cheap VPS:
    There are definite disadvantages in using cheap VPS or virtual private servers. For, you cannot get managed servers. This means that in case you have no idea how to set up & configure your own VPS, it is a huge disadvantage. This disadvantage leads us to get another disadvantage, that is, you are solely responsible of all the installation, maintenance, security measures and updates on your VPS. Thus, in the event you do not possess the high-proficiency in using the VPS to control the working of the net site, the applications used, & the server resources skillfully, you will have a major issue & your VPS becomes unmanageable. Additionally, cheap VPS hosting designs might give you a whole operating process of your own to work with, you still share hardware resources with other VPS users on the host server. Therefore, in the event you are jogging intensive programs that need high performance, you may need to make use of other technique of website hosting, such as co-location or a dedicated server.

    Remember, the great features & capabilities of the dedicated server are available for pricey fees to you. So if your web-site does not need high finish performance, cheap VPS are ideal for you. They are economical, efficient and offer excellent benefits for your website. Therefore, cheap VPS or virtual private servers can be reliable, but since it on a budget plan, do not expect as much as you would from expensive VPS plans.

  • Amazing! Its actually remarkable post, I have got much clear idea regarding from
    this article.

  • Great stuff and wowzer to all of you from me to you.

  • Excellent beat ! I would like to apprentice while you amend your site, how could i subscribe for
    a weblog web site? The account helped me a applicable deal.
    I have been a little bit familiar of this your broadcast offered vibrant
    clear idea

  • The post features verified helpful to us. It’s really informative and you're obviously quite experienced in this area. You possess opened my eyes in order to various views on this particular topic using intriguing and sound content material.

  • The write-up features proven useful to me
    personally. It’s extremely useful and you really are
    obviously extremely knowledgeable of this type.
    You have exposed my personal eye to be able to different
    opinion of this kind of topic along with intriguing and reliable written content.

  • Wow! Finally I got a web site from where I be capable of actually obtain helpful information concerning my study and knowledge.

  • Nice post. I learn something totally new and challenging on websites I stumbleupon everyday.
    It's always helpful to read through content from other writers and practice something from their web sites.

  • Woah! I'm really enjoying the template/theme of this website. It's simple, yet effective.
    A lot of times it's hard to get that "perfect balance" between superb usability and appearance. I must say that you've done a amazing job with this.
    Also, the blog loads super fast for me on Safari.
    Exceptional Blog!

  • I have been browsing on-line greater than 3 hours lately, but I by no means found any attention-grabbing article like yours.
    It is lovely value sufficient for me. Personally, if all site owners and bloggers
    made just right content as you probably did, the net will probably be much more helpful than ever before.

  • Howdy! Quick question that's entirely off topic. Do you know how to make your site mobile friendly? My weblog looks weird when viewing from my iphone4. I'm trying to find a
    template or plugin that might be able to fix this issue.

    If you have any recommendations, please share. Appreciate it!

  • What's up colleagues, its wonderful paragraph concerning tutoringand fully explained, keep it up all the time.

  • I seriously love your site.. Excellent colors & theme. Did you create this
    website yourself? Please reply back as I'm attempting to create my very own website and would love to learn where you got this from or exactly what the theme is called. Thanks!

  • Hi to every one, because I am actually eager
    of reading this web site's post to be updated on a regular basis. It includes good stuff.

  • sally slender, wat a girl

  • Outlines f¸r m¸heloses Uhren Systems

  • It's an amazing article designed for all the online users; they will obtain advantage from it I am sure.

  • First off I would like to say terrific blog! I had a quick question in
    which I'd like to ask if you don't mind. I was interested to
    find out how you center yourself and clear your thoughts prior to writing.

    I have had difficulty clearing my mind in getting my thoughts out there.
    I do enjoy writing however it just seems like the first 10 to 15 minutes are generally lost just trying to figure out how to begin.
    Any recommendations or hints? Kudos!

  • The other thing that you cannot do is to remain understood was on " What's forwards : Tool and Neal search for the make your Ways To Get Ex Back deucedly, and you testament get your Ways To Get Ex Back very soft than you imagined.

  • Undeniably believe that which you said. Your favorite reason appeared to be on
    the internet the easiest thing to be aware of. I say to you, I certainly get annoyed while people consider worries that they plainly don't know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people could take a signal. Will probably be back to get more. Thanks

  • Spot on with this write-up, I really believe that
    this website needs much more attention. I'll probably be returning to see more, thanks for the info!

  • foe the past few days back i have so many doubts in coding to use but today i really feel so happy to reading this content.

  • thats why php powned asp

  • 0 down vote

    After lots of experimenting, we think we narrowed it down. We are forced to use cookie-less session state on this system and that seems to be the problem. Our development machines have a major difference in that they have .net 4.5 installed on them. The production server as well as a few other developers only have .net 4.0 installed. If we allow a cookie, it works just fine. It seems that the paths are not being handled properly on the 4.0 machines in cookie-less session state which breaks the security trimming. Some more testing is needed to verify this. Unfortunately updating the production machine is not an option.

  • I for all time emailed this webpage post page to all my friends,
    as if like to read it then my friends will too.

  • Everything is very open with a very clear clarification of the challenges.
    It was truly informative. Your website is very helpful. Thanks for sharing!

  • A talented attorney will pull you out of this miserable condition immediately.
    That's when it is bright idea to hire a lawyer to assist you'll.

  • Life quotes compared apply a person's attribute on a person's chick.

  • I'm a writer from Dayton, United States just submitted this to a coworker who was doing a little research on this. And she in fact ordered me lunch only because I discovered it for her... lol. Actually, allow me to paraphrase this.... Thanks for the meal... But yeah, thanks for spending some time to talk about this issue here on your site.

  • When someone writes an paragraph he/she retains the thought of a user
    in his/her brain that how a user can know it. Therefore that's why this post is amazing. Thanks!

  • I used to be able to find good info from your blog posts.

  • What's Taking place i am new to this, I stumbled upon this I've discovered It positively helpful
    and it has helped me out loads. I'm hoping to give a contribution & help different users like its aided me. Great job.

  • Your advice is incredibly fascinating.

  • On sole hand, you're very much proud that he or she often is growing up. A Mom or dad ad Litem are usually a legal separation and family The legal system lawyer.

  • a whole lot worse as compared actually nagged to deaths.

Comments have been disabled for this content.