Asp.net-Mvc

MVC 角色授權

  • November 10, 2015

我正在嘗試實現一個角色授權機制來檢查目前登錄使用者的角色,如果使用者是正確的角色,他/她被允許,否則顯示錯誤視圖。

問題是,當使用者嘗試訪問控制器中的以下方法時,他確實進入了 RoleAuthorizationAttribute 類並得到了驗證,但是控制器中的方法沒有執行。

注意:使用者具有客戶端角色

控制器方法

[RoleAuthorization(Roles = "Client, Adminsitrator")]
   public ActionResult addToCart(int ProductID, string Quantity)
   {
       tempShoppingCart t = new tempShoppingCart();
       t.ProductID = ProductID;
       t.Username = User.Identity.Name;
       t.Quantity = Convert.ToInt16(Quantity);

       new OrdersService.OrdersClient().addToCart(t);
       ViewData["numberOfItemsInShoppingCart"] = new OrdersService.OrdersClient().getNoOfItemsInShoppingCart(User.Identity.Name);
       ViewData["totalPriceInSC"] = new OrdersService.OrdersClient().getTotalPriceOfItemsInSC(User.Identity.Name);
       return PartialView("quickShoppingCart", "Orders");
   }

角色認證類

[System.AttributeUsage(System.AttributeTargets.All,AllowMultiple = false, Inherited = true)]
public sealed class RoleAuthorizationAttribute : AuthorizeAttribute
{
   public override void OnAuthorization(AuthorizationContext filterContext)
   {


       List<String> requiredRoles = Roles.Split(Convert.ToChar(",")).ToList();

       List<Role> allRoles = new UsersService.UsersClient().GetUserRoles(filterContext.HttpContext.User.Identity.Name).ToList();


       bool Match = false;

       foreach (String s in requiredRoles)
       {
           foreach (Role r in allRoles)
           {
               string rName = r.RoleName.Trim().ToString();
               string sName = s.Trim();
               if (rName == sName)
               {
                   Match = true;
               }
           }
       }

       if (!Match)
       {
           filterContext.Result = new ViewResult { ViewName = "AccessDenied" };
       }

       base.OnAuthorization(filterContext);

   }
}

你能告訴我我做錯了什麼嗎

因為我在數據庫中有使用者的角色,所以我必須檢查數據庫,所以我在 global.asax 中包含了這個方法

protected void Application_AuthenticateRequest(object sender, EventArgs args)
   {
       if (Context.User != null)
       {
           IEnumerable<Role> roles = new UsersService.UsersClient().GetUserRoles(
                                                   Context.User.Identity.Name);


           string[] rolesArray = new string[roles.Count()];
           for (int i = 0; i < roles.Count(); i++)
           {
               rolesArray[i] = roles.ElementAt(i).RoleName;
           }

           GenericPrincipal gp = new GenericPrincipal(Context.User.Identity, rolesArray);
           Context.User = gp;
       }
   }

然後我可以使用正常的

[Authorize(Roles = "Client, Administrator")]

在控制器中的 actionResult 方法之上

這行得通。

引用自:https://stackoverflow.com/questions/22724798