2013-03-11 99 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