Which Authorize Attribute ?
System.Web.Http.Authorize
System.Web.Mvc.Authorize
using System.Web.Mvc // or using System.Web.Http
A typical controller
[Authorize] public class SomeController : Controller
We have controllers Annotated with [Authorize]
I just noticed that due to using namespaces the annotations technically refer to different attribute classes.
The project contains MVC controllers and WEBAPI controllers.
Which one should I use and why ? What issues might we have if I dont fix this ?
In MVC, the 'Authorize' attribute handles both authentication and authorization. In general, it works well, with the help of extension to handle AJAX calls elegantly, and to distinguish between unauthorized users and those who are not logged in.
In ASP.NET Web API authorization is implemented by using the Authorization filters which will be executed before the controller action method executed. Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated.
Alter the RegisterGlobalFilters Method in Global.asax to add an Authorize Attribute to the entire ASP.NET MVC 4 Website. You need to specify System.Web.Mvc with the Authorize Attribute because you will find an AuthorizeAttribute in System.Web.Http, too.
Here is a snippet of the OnAuthorization Method: Essentially skip authorization if you find an AllowAnonymous Attribute on the action or controller. Always fun to learn about the new features in ASP.NET MVC 4.
The OnAuthorization Method of the Authorize Attribute looks for an AllowAnonymous Attribute on the action or the controller and bypasses authorization if this is the case. Here is a snippet of the OnAuthorization Method:
You need to specify System.Web.Mvc with the Authorize Attribute because you will find an AuthorizeAttribute in System.Web.Http, too. This now secures every controller action in the entire ASP.NET MVC 4 Website except for those that use the AllowAnonymous Attribute.
You must use System.Web.Http.Authorize
against an ApiController
(Web API controller) and System.Web.Mvc.Authorize
against a Controller
(MVC controller). Since the framework runs the filters as part of the pipeline processing and the controllers expect the right filter to be applied, if you don't use the corresponding filter, authorization will not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With