Search code examples
c#asp.netasp.net-web-apiauthorize-attribute

Add IsLocal() check to single Controller in Web Api


Is there a way to add a filter/IsLocal() check to a specific controller?

I know from this answer (https://stackoverflow.com/a/30573590/1887101) I can apply a filter globally, but is there a simple way to only apply a filter to a single controller within an application of many controllers?


Solution

  • What confused me about all of this is that there are actually two different AuthorizeAttributes:

    • System.Web.Http.AuthorizeAttribute
    • System.Web.Mvc.AuthorizeAttribute (use this one for Controllers)

    First, create your LocalRequestOnly authorize attribute.

    using System.Web;
    using System.Web.Mvc;
    
    namespace myWebsite
    {
        public class LocalRequestOnlyAttribute : AuthorizeAttribute
        {
            protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                return httpContext.Request.IsLocal;
            }
        }
    }
    

    Then add [LocalRequestOnly] attribute to either a Controller or Action (it'll work on both).

    [LocalRequestOnly]
    public class HomeController : Controller
    {...}