27

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.

4
  • hi VeekKayBee, I have the similar requirement, Did you get solution for this?
    – gs11111
    Jul 16, 2014 at 7:17
  • @gs11111 Yes I got a solution from the below answers. Just go through all the solutions and you will get some idea. I cannot suggest a proper one as correct answer. All answers give my inputs to achieve this.
    – kbvishnu
    Jul 16, 2014 at 8:14
  • I went through the solution but I could not figure out how to apply it. Can you please outline the solution you applied.It will be a great help
    – gs11111
    Jul 16, 2014 at 10:16
  • @gs11111 I am so sorry I saw your comment now only :( I created a User object which contains a sub class of Permissions. Based on the access specified for each role in the page, I just created an Html.helper function returns true or false. This function will evaluates the permission settings and toggles the visibility of the control.
    – kbvishnu
    Aug 31, 2014 at 19:11

5 Answers 5

48

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

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

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");
2
  • But if I use a custom Role from my database . Then How ?
    – kbvishnu
    Jul 26, 2012 at 11:50
  • I've updated my answer. Let me know if you need additional details. I would encourage you to google the terms and find the insight as Authentication is really sensitive subject of which you should be aware of. Mar 16, 2017 at 7:13
6

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}
5

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
    }
}
3
  • But in case of a submit button . How I will hide or disable ? The L2Admin can save the data, but only L1Admin can authorize it. So L1 Admin and L2 admin can see both the buttons, but based on their permission it will hide or disabled.
    – kbvishnu
    Jul 26, 2012 at 11:49
  • Add a "#" action in form if you're not going to submit any data. Jul 26, 2012 at 11:51
  • Make a custom extension like Html.BeginForm to return form element or to return nothing. Jul 26, 2012 at 11:57
3
@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 />
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.