Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom MVC AuthorizeAttribute for ASP.NET Web API

I am trying to implement a custom authorization attribute on my Web API controllers, but came across an unexpected behavior.

     <Authorize(Users:="myUser")>
     Public Function GetTodoItems() As IQueryable(Of TodoItem)

The above code works very well: It will allow "myUser" to retrieve the items, bot nobody else is allowed access. However, when I try the same approach with my custom authorization, the entire check is skipped, and any user can access the resource. Neither the AuthorizeCore nor the OnAuthorization overridden methods in my derived class are called.

     <MyAuth(Users:="myUser")>
     Public Function GetTodoItems() As IQueryable(Of TodoItem)

The derived class inherits from System.Web.Mvc.AuthorizeAttribute, and the project is deployed on IIS, with Windows Authentication & Impersonation enabled, and Anonymous Authentication disabled.

If I add the same custom authorization to an MVC Controller, then it works. But on the API Controllers, nothing. If the Authorize attribute wouldn't have worked either, it would have made more sense. Am I missing something? Is this an expected behavior, or a bug in the Beta?

like image 580
Szilard Muzsi Avatar asked Feb 28 '12 13:02

Szilard Muzsi


People also ask

Does ASP Net Web API support MVC features?

Asp.Net Web API is a new framework and part of the core ASP.NET framework. The model binding, filters, routing, and other MVC features exist in Web API are different from MVC and exists in the new System.

How do I provide authentication in Web API?

To access the web API method, we have to pass the user credentials in the request header. If we do not pass the user credentials in the request header, then the server returns 401 (unauthorized) status code indicating the server supports Basic Authentication.


1 Answers

You should use System.Web.Http.AuthorizeAttribute from System.Web.Http.dll for Web API instead of System.Web.Mvc.AuthorizeAttribute.

That is, because namespace System.Web.Http.AuthorizeAttribute is derived from AuthorizationFilterAttribute. The filters are handled automatically by the Web API. In my own implementation I derived directly from AuthorizationFilterAttribute for handling of the basic HTTP authentication.

like image 167
paulius_l Avatar answered Oct 06 '22 11:10

paulius_l