1

My controller is using an attribute at class level which allows only one role to access. This controller has more than 20 actions. But for only one action I need one more role to get access. I have declared the attribute filter at class level so that it is working fine for all the actions within the controller class. But now I want to override this one for only one action within the same controller. Is there any possibility for that? I'm using .Net version 4.5.

Filter attribute implementation goes like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class RequireModulePermissionAttribute : AuthorizeAttribute
{
   //code goes here
}

Controller class:

[RequireModulePermission("Admin")]
public class AdministrationController : Controller
{
    [HttpPost]
    [RequireModulePermission("Admin","Supervisor")]
    public ActionResult CreateUser(UserViewModel userVM)
    {
       //code goes here
    }   
}
Nani
  • 1,018
  • 3
  • 16
  • 32

2 Answers2

5

Have a look at this answer (look at case 2) https://stackoverflow.com/a/16713334/2564920

Essentially you will need a second attribute to represent the override.

So you attributes become:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class RequireModulePermissionAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var action = filterContext.ActionDescriptor;
            if (action.IsDefined(typeof(OverrideRequireModulePermissionAttribute ), true)) return;
            //code goes here
        }
    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class OverrideRequireModulePermissionAttribute : AuthorizeAttribute
    {
       public override void OnAuthorization(AuthorizationContext filterContext)
       {
           base.OnAuthorization(filterContext);
       }
    } 

The you use it like

[RequireModulePermission("Admin")]
public class AdministrationController : Controller
{
    [HttpPost]
    [OverrideRequireModulePermission("Admin","Supervisor")]
    public ActionResult CreateUser(UserViewModel userVM)
    {
       //code goes here
    }   
}
Community
  • 1
  • 1
Alan Tsai
  • 2,367
  • 1
  • 9
  • 15
0

There's an alternative that you can actually set AllowMultiple = false.

In this way, only 1 filter will take effect following the filter execution order: Global -> Controller -> Action.

Shawn Teng
  • 61
  • 2