Sometimes a web site needs to limit access to its services based on a user’s role. ASP.NET MVC allows you to leverage role-based security so that links are shown or hidden based on a user’s privileges. And all with no JavaScript!
First, in your _Layout.cshtml file add Razor code to render any links that should be visible to authenticated users, like so:
<nav>
<ul>
<li>@Html.ActionLink("Home", "Index", "Home")</li>
</ul>
</nav>
Next, add an action to the Home controller that will query roles assigned to the user. We will use the controller’s ViewBag property to record which links will be available or hidden.
[ChildActionOnly]
public ActionResult CheckForPrivilegedPermissions()
{
// check if user is allowed to access functionality that requires elevated privileges
if (User.Identity.IsAuthenticated)
{
IEnumerable<Role> userRoles
= _authService.GetRolesForUser(User.Identity.Name).ToList();
ViewBag.ShowNewRecordLinks = userRoles.Contains(Role.Creator);
ViewBag.ShowUserAdminLinks = userRoles.Contains(Role.UserAdmin);
ViewBag.ShowViewRecordsLinks = userRoles.Contains(Role.Reader);
// show the links
return PartialView("_PrivilegedLinks");
}
// return nothing
return new EmptyResult();
}
This action will return an EmptyResult if the user is not authenticated. Otherwise, it will return a PartialView result, which injects a snippet of HTML into the markup. Let’s look at this partial view, named _PrivilegedLinks.cshtml.
@if (ViewBag.ShowNewRecordLinks == true)
{
<li>
<a href="#">Add New</a>
<div>
@Html.ActionLink("This", "Add", "This")
@Html.ActionLink("That", "Add", "That")
@Html.ActionLink("Other", "Add", "Other")
</div>
</li>
}
@if (ViewBag.ShowViewRecordsLinks == true)
{
<li>
<a href="#">View</a>
<div>
@Html.ActionLink("This", "Index", "This")
@Html.ActionLink("That", "Index", "That")
@Html.ActionLink("Other", "Index", "Other")
</div>
</li>
}
@if (ViewBag.ShowUserAdminLinks == true)
{
<li>
@Html.ActionLink("User Admin", "Index", "UserAdmin")
</li>
}
Here the ViewBag values set in the Home controller dictate the HTML the partial view will render. To tie the whole thing together, return to _Layout.cshtml and add a Razor helper that will call the controller action each time a page is loaded.
<nav>
<ul>
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<!-- new -->
@Html.Action("CheckForPrivilegedPermissions", "Home")
</ul>
</nav>
And that’s that. Dynamically rendered links based on user permission levels, and all done with basic functionality provided by the MVC framework.
I hope you enjoyed my first post. Thanks for reading it!