2016-10-04 75 views
1

我正在使用第一次使用角色授權的項目,但無法使其工作。爲嵌套在組中的用戶角色設置授權

問題是項目的設置方式是當創建一個新用戶時,它們被添加到一個組中。這些組包含一個或多個角色。 例如,組「ReadOnly」包含角色「userReadOnly」和「groupsReadOnly」(該用戶可以進入頁面用戶和組,看到數據但不編輯它)

我做的部分得到是控制器中的[Authorize(Roles = "..., ...")]和視圖中的@if(user.IsInRole("..."),但是當我將其添加到項目中時,事情就停止了。我知道我需要創建一個自定義AccountRoleProvider,但在這裏我卡住了。我不明白如何做到這一點,我不明白如何調整在線找到的(標準)提供商以適合我的項目。非常感謝您向正確的方向推動,或解釋提供者的實際行爲。

回答

0

要創建自定義授權篩選器,您需要在解決方案中創建一個文件夾,並在其中添加一個名爲AuthorizedRoles.cs的文件。

AuthorizedRoles.cs文件爲:

sealed class AuthorizedRoles : ActionFilterAttribute 
    { 
     public string Roles { get; set; } 

     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      var status = false; 
      string[] roles = Roles.Split(','); 
      var currentUserRole = Session.UserRole; // Get here the role of the user 
      var Role = ""; 
      switch (currentUserRole) 
      { 
       case 1: 
        Role = "Role1"; 
        break; 
       case 2: 
        Role = "Role2"; 
        break; 
       case 3: 
        Role = "Role3"; 
        break; // Check here for more role 
       default: 
        break; 
      } 

      if (Role != ""){ 
       foreach (var role in roles) 
       { 
        if (role.Contains(currentRoleName)) 
        { 
         status = true; 
        } 
       } 
      } 

     if (status == false)//That means user is not in the role, so redirect it to the new controller returning a view showing information that you are not autorized 
      { 
       if (filterContext.HttpContext.Request.IsAjaxRequest()) 
       { 
        //The request can be ajax callso it will redirect to another ajax method 
        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new 
        { 
         controller = "ControllerName", 
         action = "AjaxActionName", 
         area = "" 
        })); 
       } 
       else 
       { 
      filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new 
        { 
         controller = "ControllerName", 
         action = "ActionName", 
         area = "" 
        })); 
} 
     } 
     base.OnActionExecuting(filterContext); 
     } 

} 

重定向方法將像;

public ActionResult ActionName() 
     { 
      return View(); //Create view for this action 
     } 

public JsonResult AjaxActionName() 
     { 
      return Json(new { status = false, message = "Unauthorized access." }, JsonRequestBehavior.AllowGet); 

     } 

以上您要檢查的任何方法可以用來調用自定義授權過濾:

//This method will execute only if the user have Role1 and Role2 other wise redirected to other no permission methods before the action executes. 
    [AuthorizedRoles(Roles = "Role1,Role2")] 
     public ActionResult NeedPermissionAction(int id) 
     { 

}