How to efficiently test if action is decorated with an attribute (AuthorizeAttribute)?

10,588

Solution 1

You can simply use filterContext.ActionDescriptor.GetCustomAttributes

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    bool hasAuthorizeAttribute = filterContext.ActionDescriptor
        .GetCustomAttributes(typeof(AuthorizeAttribute), false)
        .Any();

    if (hasAuthorizeAttribute)
    { 
        // do stuff
    }

    base.OnActionExecuting(filterContext);
}

Solution 2

var hasAuthorizeAttribute = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), false);

http://msdn.microsoft.com/en-us/library/system.web.mvc.actiondescriptor.isdefined%28v=vs.98%29.aspx

Share:
10,588

Related videos on Youtube

EBarr
Author by

EBarr

Yep, I code in a tux. Don't you?

Updated on June 04, 2022

Comments

  • EBarr
    EBarr about 2 years

    I'm using MVC and have a situation where in my OnActionExecuting() I need to determine if the Action method that is about to execute is decorated with an attribute, the AuthorizeAttribute in particular. I'm not asking if authorization succeeded/failed, instead I'm asking does the method require authorization.

    For non-mvc people filterContext.ActionDescriptor.ActionName is the method name I'm looking for. It is not, however, the currently executing method; rather, it is a method that will be executed shortly.

    Currently I have a code block like below, but I'm not terribly pleased with the looping prior to every action. Is there a better way to do this?

    System.Reflection.MethodInfo[] actionMethodInfo = this.GetType().GetMethods();
    
    foreach(System.Reflection.MethodInfo mInfo in actionMethodInfo) {
        if (mInfo.Name == filterContext.ActionDescriptor.ActionName) {
            object[] authAttributes = mInfo.GetCustomAttributes(typeof(System.Web.Mvc.AuthorizeAttribute), false);
    
            if (authAttributes.Length > 0) {
    
                <LOGIC WHEN THE METHOD REQUIRES AUTHORIZAITON>
    
                break;
            }
        }
    }
    

    This is a little like the slightly mistitled "How to determine if a class is decorated with a specific attribute" but not quite.

  • Jaime
    Jaime over 6 years
    Beware! if it's the controller the one with the [Authorize] attribute, this won't work. Besides, the action can be decorated with [AllowAnonymous]. I have used this instead: var hasAuthorizeAttribute = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAtt‌​ribute), false) || (filterContext.ActionDescriptor.ControllerDescriptor.IsDefin‌​ed(typeof(AuthorizeA‌​ttribute), false) && !filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonym‌​ousAttribute), false));
  • Vladislav Kostenko
    Vladislav Kostenko over 6 years
    this is not about valid Authorization check, the example about efficient Attribute check. And probably you are right, it could be other fatctors that affect Authorization as well.