用户和角色管理MVC4

我在MVC4中编写了一个定制的Web系统,该系统的一部分需要Admin用户来管理公司中的角色和用户,以便为系统的某些区域提供访问权限。 系统中有系统模块:

销售生产

管理团队希望能够在系统中创建角色并将权限应用于这些角色。 例如,销售角色将被拒绝访问生产,但销售经理可以拥有对生产的只读访问权限。

我正在寻找一个管理此屏幕的最佳方法示例。 管理员需要

  • 创建角色
  • 创建用户
  • 分配角色
  • 为系统中的模块和操作分配角色权限

我还将如何在Controller级别实现它,因为角色需要动态分配?

[Authorize(Roles="Sales")] // needs to be dynamic public ActionResult SalesIndex(){ return View(); } 

任何想法,将不胜感激

谢谢

您需要像这样创建自定义AuthorizeAttribute

 public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var userIdentity = httpContext.User.Identity; if (!userIdentity.IsAuthenticated) return false; var rd = httpContext.Request.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); if(currentAction == "SalesIndex") { return IsUserIsInRoleForTheView(userIdentity.Name); } return true; } } [CustomAuthorize] public ActionResult SalesIndex() { return View(); } 

一种方法是使数据模型具有两个级别的角色:

  • GroupRoles(例如销售)。 用户是组角色的成员,即有MN关系用户 – GroupRoles。

  • PermissionRoles。 表示由应用程序控制的资源或操作或资源的细粒度权限。 GroupRoles和PermissionRoles之间存在MN关系。

然后,您将拥有一个自定义管理UI,以将用户分配给GroupRoles和GroupRoles到PermissionRoles。

您还可以使用自定义RoleProvider来“展平”此模型,即GetRolesForUser方法返回用户的所有PermissionRoles(通过他的GroupRole成员资格)。

然后,您可以使用标准.NET API进行授权,而不需要自定义Authorize属性:

 [Authorize(Roles="SomeAction")] // for an MVC Controller [PrincipalPermission(SecurityAction.Demand, Role = "SomeAction")] // For a method in the BLL Thread.CurrentPrincipal.IsInRole("SomeAction") // in code