2013-03-11 90 views
2

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

销售 生产

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

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

  • 系统

此外,我怎么会在控制器级别实现它创建角色

  • 创建用户
  • 分配角色
  • 分配的角色权限模块和行动因为角色需要动态分配?

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

    任何想法,将不胜感激

    感谢

  • 回答

    3

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

    有道理,感谢这个! – CR41G14 2013-03-11 13:49:17

    0

    一个做到这一点的方法是有两个层面的数据模型角色:

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

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

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

    您还将拥有一个自定义RoleProvider,可以“平滑”此模型,即GetRolesForUser方法会为用户返回所有PermissionRoles(通过其GroupRole成员资格)。

    然后可以使用标准的.NET API的授权,也不需要自定义的授权属性:

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