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

时间:2021-12-08 19:57:37

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.

我有一个菜单表,有菜单详细信息。有一些功能,如删除,编辑,它们是根据当前用户的角色显示的,在顶层菜单中不可用。在列出数据时,删除,编辑链接放在表中。这也包括,对于那些类型的条目,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.

如果Admininstrator正在登录,则可以看到所有菜单。如果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.

我为身份验证创建了一个自定义属性,之后我查询数据库并根据Contoller和Action获取用户的权限(表Menu连接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.

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

4 个解决方案

#1


38  

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

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

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

#2


10  

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

选项2 - 在您自己创建AuthCookie的情况下指定userData中的角色,然后在Global.asax.cs文件的Application_PostAuthenticateRequest方法上将HttpContext.Current.User设置为新的GenericPrinciple(从authcookie的userdata获取userrole) - 保留实现你去谷歌。这应该适用于以后

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

#3


5  

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

选项1创建授权的操作链接扩展。演示

Create a custom html Authorized ActionLink and call as below

创建自定义html授权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 2 Create a static function and check before action link

选项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}

#4


4  

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

#1


38  

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

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

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

#2


10  

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

选项2 - 在您自己创建AuthCookie的情况下指定userData中的角色,然后在Global.asax.cs文件的Application_PostAuthenticateRequest方法上将HttpContext.Current.User设置为新的GenericPrinciple(从authcookie的userdata获取userrole) - 保留实现你去谷歌。这应该适用于以后

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

#3


5  

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

选项1创建授权的操作链接扩展。演示

Create a custom html Authorized ActionLink and call as below

创建自定义html授权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 2 Create a static function and check before action link

选项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}

#4


4  

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