Reputation: 2009
I have a project with both MVC and Web API controllers in it. It uses Windows Auth. However I want to protect a particular Web API action with a custom attribute. I have created the following just to get the basic flow set up (ultimately it will check the users IP address):
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
namespace UoB.People.UserInterface.Mvc.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class IPAuthorize : AuthorizationFilterAttribute
{
protected bool AuthorizeCore(HttpContextBase httpContext)
{
return true;
}
}
}
I have decorated my Web API action with a call to this attribute. Problem is, when I run my code locally, the attribute code is never hit. The action is. This particular action belongs to a controller which does not use Windows Auth.
Why is my attribute not being called? Does it need to be registered somewhere? Is there a conflict because my project contains both MVC and Web API controllers? Have I made a simple error somewhere?
Thanks.
Upvotes: 1
Views: 2774
Reputation: 2009
Finally figured out my problem. I actually needed to override OnAuthorization and AuthorizeCore. The following example demonstrates this:
public class IPAuthorize : AuthorizeAttribute
{
public string AuthorisedIPs { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
if (AuthorizeCore((HttpContextBase)actionContext.Request.Properties["MS_HttpContext"]))
return;
base.HandleUnauthorizedRequest(actionContext);
}
protected bool AuthorizeCore(HttpContextBase httpContext)
{
// Logic here.
}
}
Hope this helps if anyone else is having trouble.
Upvotes: 1
Reputation: 4668
You need to register your attribute in RegisterGlobalFilters in your FilterConfig.cs class.
Hope this helps.
Upvotes: 2