【问题标题】:User and Role Management MVC4用户和角色管理 MVC4
【发布时间】:2013-02-26 16:47:20
【问题描述】:

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

销售 生产

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

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

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

另外,由于需要动态分配角色,我将如何在控制器级别实现它?

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

    return View();

}

任何想法将不胜感激

谢谢

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    您需要像这样创建自定义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();
    }
    

    【讨论】:

      【解决方案2】:

      做到这一点的一种方法是拥有一个具有两个角色级别的数据模型:

      • GroupRoles(例如销售)。用户是组角色的成员,即存在 M-N 关系 Users - GroupRoles。

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

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

      您还将有一个自定义 RoleProvider 来“展平”此模型,即 GetRolesForUser 方法返回用户的所有 PermissionRole(通过他的 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
      

      【讨论】:

        猜你喜欢
        • 2011-03-20
        • 1970-01-01
        • 2017-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 2015-11-02
        相关资源
        最近更新 更多