0

I have two user types-
-Admin
-Visitor
If the user type is "Visitor" then the Sub1 node will not be there in the menu.But the below code doesn't work to hide/remove the specific node.
My Sitemap looks like:

<mvcSiteMapNode title="Home" controller="Home" action="Index">
<mvcSiteMapNode title="Site Map Test" controller="SitemapTest"action="Index" key="sitemaptestnode"> 
<mvcSiteMapNode title="Sub1" controller="SitemapTest" action="Sub1" key="Childsitemaptestnode1" visibility ="false"/>
<mvcSiteMapNode title="Sub2" controller="SitemapTest" action="Sub2" key="Childsitemaptestnode2"/>
<mvcSiteMapNode title="Sub3" controller="SitemapTest" action="Sub3" />
</mvcSiteMapNode>
</mvcSiteMapNode>

From the Layout.cshtml I have called

@Html.Action(“RenderMenu”,”Menu”);


Public void RenderMenu(){
var node = MvcSiteMapProvider.SiteMaps.Current.FindSiteMapNodeFromKey("Childsitemaptestnode1");
If (node.title =="Sub1"){
//Function to get the user type from database
String UserType=GetUserTypes();
If(UserType=="Visitor"){
//Hide Sub1 node from Menu
node.Attributes["visibility"]="!*";  }  
}}
dev kolkata
  • 55
  • 1
  • 1
  • 9

1 Answers1

0

The most common way to handle this is to use group-based security and use the AuthorizeAttribute.

However, in this simple scenario you don't even really need groups. Adding the AuthorizeAttribute to your action method will automatically deny any users that are not logged in.

    [Authorize]
    public ActionResult Sub1()
    {
        return View();
    }

This assumes you have setup a security framework that implements IPrincipal and IIdentity (of which ASP.NET Identity and Membership both do). You can get the basic framework for one of these options by using one of the default templates created by Visual Studio and copying over the relevant bits (AccountController, ManageController, related views, and related startup code) into your project.

All that would be required in MvcSiteMapProvider would be to enable security trimming.

Internal DI (web.config)

<appSettings>
    <add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/>
</appSettings>

External DI (MvcSiteMapProvider Module)

bool securityTrimmingEnabled = true; // Near the top of the module

That will make the nodes automatically hide when the user doesn't have access and AuthorizeAttribute will actually secure the URL so the user can't navigate there directly.

Changing visibility of a link doesn't secure anything, but if that is all you want, you should refer to the visibility provider section of the documentation.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212