title: ASP.NET MVC4 override OnAuthorization to allow whitelist of roles
body: <p>I have an ASP.NET MVC4 site with two types of roles: Administrator and Partner.</p>
  
  <p>Basically all access to the site requires a user to authenticated and have role Administrator.
  Therefore I do this in FilterConfig.cs (called from Global.asax):</p>
  
  <pre><code>public class FilterConfig {
      public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
          filters.Add(new HandleErrorAttribute());
          filters.Add(new AuthorizeAttribute { Roles = "Administrator" }); // default deny
      }
  }
  </code></pre>
  
  <p>For one controller however I want grant access to users with the Partner role but wihtout the Adminstrator role. I know I could do this by not using the global filter and instead set Authorize attributes on each Controller or Action, but I would like a white list approach instead where all acces by default requires "Administrator" role and then use some form of white listing.</p>
  
  <p>I have tried using a controller where I override OnAuthorization like this:</p>
  
  <pre><code>public class MyController : Controller {
      protected override void OnAuthorization(AuthorizationContext filterContext) {
          if (User.Identity.IsAuthenticated) {
              var attributes = new List&lt;AllowRolesAttribute&gt;();
              attributes.AddRange(filterContext.ActionDescriptor.GetCustomAttributes(true).OfType&lt;AllowRolesAttribute&gt;());
              attributes.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true).OfType&lt;AllowRolesAttribute&gt;());
              foreach (var authorizationAttribute in attributes) {
                  foreach (var role in authorizationAttribute.Roles.Split(',')) {
                      if (User.IsInRole(role))
                          return; // Skip authorization because user has one of the allowed roles.
                  }
              }
          }
          base.OnAuthorization(filterContext);
      }
  }
  </code></pre>
  
  <p>I then define the controller like this:</p>
  
  <pre><code>[AllowRoles(Roles = "Partner")]
  public class HomeController : MyController
  {
      ...
  </code></pre>
  
  <p>But this does not work. When I access this controller with a user with role "Partner" I can follow the code into the inner return statement, but the user is still redirected to the login page instead of being authorized. What am I missing here?</p>