Alex Alex - 5 months ago 17
C# Question

MVC Webapp hide/show website tabs with Azure AD Roles

I have an MVC WebApp where I am successfully authenticating and pulling Azure AD Roles into my app. How can I show or hide navbar tabs like 'home' 'about' and so on in my _Layout.cshtml file, based on that role?

I can authorize pages in the controller with

[Authorize(Roles = "")]
but I want to hide at the navbar level. What line(s) of code am I missing to make this dynammic?

Here is the code in my _Layout.cshtml file that I am looking to make this happen:

<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("My Project", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>


Thanks in advance for the help!

Answer Source

On MVC, you have the User object, which gives you the information about the logged user. Just use the User.IsInRole(roleName) method, it should work.

Example:

<div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        @Html.ActionLink("My Project", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    </div>
    <div class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
            <li>@Html.ActionLink("Home", "Index", "Home")</li>
            <li>@Html.ActionLink("About", "About", "Home")</li>
            @if(User.IsInRole("Admin"))
            {
                //Only the user with "Admin" role can see this
                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
            }
        </ul>
        @Html.Partial("_LoginPartial")
    </div>