title: MVC Role Authorization
body: <p>I am trying to implement a role authorization mechanism which checks the roles of the current logged in user, if the user is in the right role, he/she is allowed, else display error view.</p>
  
  <p>The problem is that when the user tries to access the below method in the controller, he does get into the RoleAuthorizationAttribute class and gets verfied but then the method in the controller is not executed. </p>
  
  <p>Note : the user has the Client role </p>
  
  <p>Controller method </p>
  
  <pre><code>[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");
      }
  </code></pre>
  
  <p>Role Authentication class </p>
  
  <pre><code>[System.AttributeUsage(System.AttributeTargets.All,AllowMultiple = false, Inherited = true)]
  public sealed class RoleAuthorizationAttribute : AuthorizeAttribute
  {
      public override void OnAuthorization(AuthorizationContext filterContext)
      {
  
  
          List&lt;String&gt; requiredRoles = Roles.Split(Convert.ToChar(",")).ToList();
  
          List&lt;Role&gt; 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);
  
      }
  }
  </code></pre>
  
  <p>Could you please tell me what I am doing wrong </p>