简体   繁体   中英

ASP.NET MVC - How to hide or Show a link/button based on logged in User's Role permission?

I am using ASP.NET MVC4.

This is my userroles

1. Administrator
2. L1 Admin
3. L2 Admin

Administrator group users have permission for Settings(used adding , permission settings). View Logs, Error Reports etc.

If a user is a member for Administrator group, he can see only menus which are related ti above settings.

I have a menu table, having menu details. There are some functions like Delete,Edit which are shown based on the role of the current user and not availble in the top Menu . Delete,Edit link is placed inside a table while Listing the data. That also included and for that types of entry , IsVisible is false.

MenuID - MenuName - Controller - Action - ParentID - IsVisible

I have a roleMenu table, having menu which are assigned to each roles.

RoleID - MenuID

If Admininstrator is logging in, he can see all menus. If L1Admin is logging in , he can only see menu which are assigned to him.

I created a custom attribute for authentication and after that I query the database and get the permission for the user based on the Contoller and Action (table Menu joins RoleMenu). So I can restrict a request if the user tries access an action through URL by typing in browser.

If I am entering as L1Admin, I can only see the List Pages and the menu is created correclty. In the list page I am using for listing. So how can I hide the Edit/Details link based on the Permission of logged in user.

 <div style="float: left">
        <table width="50%">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                </th>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td style="width:30%;">
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td style="width:20%;">
// I need to hide EDIT/DELETE based on the permission setting of Current logged in user.
                        @Html.ActionLink("Edit", "Edit", new { id = item.ID }) | 
                        <a href="Server/@item.ID">Details</a> |
                        @Html.ActionLink("Delete", "Delete", new { id = item.ID })
                    </td>
                </tr>
            }
        </table>
    </div>

Thanks in advance.

EDIT

I am storing the permission details in a database.

For example, you can do it in a way like this:

@if (ViewContext.HttpContext.User.IsInRole("Your role"))
{
    // Do something here
}

Option 1 - Considering you are using asp .net membership.

@if (Roles.IsUserInRole("Administrator"))
{ 
  //show link 
}
else
{
  //hide link/button
}

Option 2 - Specify roles in userData in case you are creating AuthCookie on your own and later set HttpContext.Current.User to new GenericPrinciple(fetch userrole from userdata of authcookie) on Application_PostAuthenticateRequest method of Global.asax.cs file - Leaving the implementation on you to google.

This should work later

System.Web.HttpContext.Current.User.IsInRole("RoleName");

Because of storing the permission details in a database, You can check permission as the following ways

Option 1 Create an authorized action link extension . Demo

Create a custom html Authorized ActionLink and call as below

 <ul id="menu">              
    <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
    <li><%: Html.ActionLink("About", "About", "Home")%></li>

    // Next line What you are looking for
    <li><%: Html.ActionLinkAuthorized("The Privilege Zone", "ThePrivilegeZone", "Home", true)%></li>
</ul>

Note : for a better security you need a custom action filter to check all the request is authorized.

Option 2 Create a static function and check before action link

public static bool IsUserInRole(string rolenamefrom session)
{
    // Check the user have the privilege then return true/false
}

@if (IsUserInRole("Administrator"))
{ //show link }
else
{//hide link/button}

Make a custom helper extension like this, where CustomMethodForRetrievingUserFlag() returns User Permissions, CustomMethodForRetrievingFlags returns allowed permissions for an action for example. Good luck.

Usage from view: @Url.CustomUrl("Home", "Index")

[Flags]
public enum AuthorizeFlags
{
    Administrator = 1,
    L1 = 2,
    L2 = 4
}

public static class UrlHelperExtensions
{
    public static MvcHtmlString CustomUrl(this UrlHelper urlHelper, string controllerName, string actionName, object routeValues = null)
    {
        var actionFlag = CustomMethodForRetrievingFlags(actionName);
        var userFlag = CustomMethodForRetrievingUserFlag();

        if ((actionFlag & userFlag) == userFlag)
        {
            return new MvcHtmlString(urlHelper.Action(actionName, controllerName, routeValues));
        }

        return new MvcHtmlString(String.Empty);
    }

    private static AuthorizeFlags CustomMethodForRetrievingUserFlag()
    {
        return AuthorizeFlags.L2;
    }

    private static AuthorizeFlags CustomMethodForRetrievingFlags(string actionName)
    {
        return (AuthorizeFlags.Administrator | AuthorizeFlags.L1); // test stub
    }
}
@if (User.Identity.IsAuthenticated)// check whether the user is authenticated or not
    {
        if (User.IsInRole("HR"))//Check wether the user is in that role
        {
            //Contents to be displayed for that Role!
            //some sample content which will be displayed to the user of a Role HR
            <div>
                <h5><strong>HR Approval</strong></h5>
            </div>
            <div>
                <button type="button" name="btnApprove" id="btnApprove">Approve</button>
                <button type="button" name="btnReject" id="btnReject">Reject</button>
            </div>
            <br />
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM