C# ASP.NET MVC - 如何根据登录用户的角色权限隐藏或显示链接/按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11668261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:43:42  来源:igfitidea点击:

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

c#asp.net-mvcasp.net-mvc-3

提问by kbvishnu

I am using ASP.NET MVC4.

我正在使用 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.

我有一个菜单表,有菜单详细信息。有一些功能,如删除、编辑,它们根据当前用户的角色显示,在顶部菜单中不可用。列出数据时,删除、编辑链接放置在表中。这也包括对于那种类型的 entry , IsVisible 是假的。

MenuID - MenuName - Controller - Action - ParentID - IsVisible

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

我有一个 roleMenu 表,其中有分配给每个角色的菜单。

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.

如果管理员正在登录,他可以看到所有菜单。如果 L1Admin 正在登录,他只能看到分配给他的菜单。

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.

我创建了一个用于身份验证的自定义属性,然后我查询数据库并根据控制器和操作(表菜单加入 RoleMenu)获取用户的权限。因此,如果用户尝试通过在浏览器中键入 URL 来访问操作,我可以限制请求。

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.

如果我以 L1Admin 身份进入,我只能看到列表页面并且菜单创建正确。在我用于列表的列表页面中。那么如何根据登录用户的权限隐藏编辑/详细信息链接。

 <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.

我将权限详细信息存储在数据库中。

回答by laszlokiss88

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

例如,您可以通过以下方式进行操作:

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

回答by Alex Yaroshevich

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

制作一个像这样的自定义帮助器扩展,例如,CustomMethodForRetrievingUserFlag() 返回用户权限,CustomMethodForRetrievingFlags 返回允许的操作权限。祝你好运。

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

视图中的用法:@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
    }
}

回答by RollerCosta

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

选项 1- 考虑到您使用的是 asp .net 会员资格。

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

Option 2- Specify roles in userData in case you are creating AuthCookieon 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

选项 2- 如果您自己创建AuthCookie,然后在 Global.asax.cs 文件的 Application_PostAuthenticateRequest 方法上将 HttpContext.Current.User 设置为新的 GenericPrinciple(从 authcookie 的用户数据中获取用户角色),请在 userData 中指定角色- 将实现留在你去谷歌。

这应该在以后工作

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

回答by Nikhil K S

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

由于将权限详细信息存储在数据库中,您可以通过以下方式检查权限

Option 1Create an authorized action link extension. Demo

Option 1创建授权操作链接扩展演示

Create a custom html Authorized ActionLink and call as below

创建一个自定义的 html Authorized ActionLink 并调用如下

 <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 2Create a static function and check before action link

Option 2创建一个静态函数并在操作链接之前检查

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}