Alisson Reinaldo Silva
Alisson Reinaldo Silva

Reputation: 10695

Override Global Authorize in Controller instead of Action

I created a custom authorize, which is ignored when an action has [Authorize]:

public class MyGlobalAuthorizeAttribute: AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // check if action is decorated with an Authorize...
        var action = filterContext.ActionDescriptor
        if (action.IsDefined(typeof(AuthorizeAttribute), true))
            return;

        base.OnAuthorization(filterContext);
    }

}

...then I configured it in the global filters, only allowing admins by default:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new MyGlobalAuthorizeAttribute() { Roles = "Admin" });
    }
}

If I decorate an action like this:

public class MyController: Controller
{
    [Authorize] // non-admins can access this action..
    public ActionResult Index()
    {
    }
}

...it works fine. However, if I put the [Authorize] in controller, MyGlobalAuthorizeAttribute won't detect it.

I found many examples of overriding, but all of them is about an action overriding a controller or a global authorize, but not a controller overriding a global authorize.

Is it possible to achieve this?

Upvotes: 0

Views: 536

Answers (1)

user47589
user47589

Reputation:

You also need to check the ControllerDescriptor:

var action = filterContext.ActionDescriptor;
if (action.IsDefined(typeof(AuthorizeAttribute), true))
    return;

if (action.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
    return;

Documentation for ControllerDescriptor.IsDefined(...)

Upvotes: 4

Related Questions