Reputation: 9285
I use a WebApi Service with custom Authorization. This is the AuthorizationAttribute: (to keep it as simple as possible I removed all logic and just try to send a 401):
public class Auth : AuthorizeAttribute
{
private readonly List<Permissions> _requiredPermissions;
public Auth(params Permissions[] permissions)
{
_requiredPermissions = permissions.ToList();
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
Inside my Controller-Actions I call the Auth the following way:
public class CustomerController : ApiController
{
[Auth(Permissions.CanLogin, Permissions.IsAdmin)]
public HttpResponseMessage Get(Guid id)
{
// Do something
}
}
(Permissions
is just a simple enum.)
I can see that the constructor from Auth()
is called at program start. But the "OnAuthorization()
" method never gets called.
What am I missing there?
Upvotes: 2
Views: 1552
Reputation: 9285
The problem was that the authorization I implemented was from MVC. But for web api, another authorization is needed, which looks nearly the same but differs a bit.
First I had to remove the reference to MVC in the custom authorization class and use web.http instead:
So. I had to remove this:
using System.Web.Mvc
and instead add this:
using System.Web.Http;
Then the OnAuthorization-Method needs another Parameter. So I had to change this:
public override void OnAuthorization(AuthorizationContext filterContext)
to this:
public override void OnAuthorization(HttpActionContext filterContext)
(HttpActionContext is inside the System.Web.Http.Controllers - namespace)
It seems the authorizaton stopped working after I installed the most current version of WebApi using the nuget-console inside a "ASP.NET MVC 4 Web Application" with Web Api Options enabled.
Upvotes: 5