Search code examples
asp.net-mvcasp.net-web-apiaction-filter

Authorisation Action Filters for WebAPI


I have an MVC 4 solution which I have been applying authorisation action filters onto various controllers to some additional checks before allow access through to certain controllers.

 public class AuthoriseUserViewAccess : FilterAttribute , IAuthorizationFilter
{

    public void OnAuthorization(AuthorizationContext filterContext)
    {
    }
 }

This has been working well with my controllers and actions.

But I also wanted to the same thing with the WEB API controllers I am using in the same solution.

I have tried applying the AuthoriseUserViewAccess attribute to my apicontrollers, but the onAuthorisation method never seems to get invoked.

Should this work with WebAPI Controllers too, or is there another approach for achieving the same thing with WEBAPI.


Solution

  • I used this a a test and the OnAuthorization gets called. The attribute is applied on my webapi. Maybe try to inherit from System.Web.Http.AuthorizeAttribute.

        public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
    {
        public override void OnAuthorization(
               System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            // Do other checks
            var ok = false;
            if (!ok)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
                return;
            }
    
            base.OnAuthorization(actionContext);
        }
    }