2016-10-04 51 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) 
     { 

}