Kramer00
Kramer00

Reputation: 1187

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.

Upvotes: 1

Views: 2497

Answers (1)

Kenny Tordeur
Kenny Tordeur

Reputation: 212

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);
    }
}

Upvotes: 3

Related Questions