[英]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.我正在使用 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).我创建了一个用于身份验证的自定义属性,然后我查询数据库并根据控制器和操作(表菜单加入 RoleMenu)获取用户的权限。 So I can restrict a request if the user tries access an action through URL by typing in browser.
因此,如果用户尝试通过在浏览器中键入 URL 来访问操作,我可以限制请求。
If I am entering as L1Admin, I can only see the List Pages and the menu is created correclty.如果我以 L1Admin 身份进入,我只能看到列表页面并且菜单创建正确。 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.选项 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.选项 2 - 在 userData 中指定角色,以防你自己创建AuthCookie ,然后在 Global.asax.cs 文件的 Application_PostAuthenticateRequest 方法上将 HttpContext.Current.User 设置为新的 GenericPrinciple(从 authcookie 的用户数据中获取用户角色) - 将实现留在你去谷歌。
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 . Option 1
创建授权操作链接扩展。 Demo 演示
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 2
Create 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}
Make a custom helper extension like this, where CustomMethodForRetrievingUserFlag() returns User Permissions, CustomMethodForRetrievingFlags returns allowed permissions for an action for example.制作一个像这样的自定义帮助器扩展,例如,CustomMethodForRetrievingUserFlag() 返回用户权限,CustomMethodForRetrievingFlags 返回允许的操作权限。 Good luck.
祝你好运。
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
}
}
@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 />
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.