67

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 ?

phil soady
  • 11,043
  • 5
  • 50
  • 95

1 Answers1

88

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.

  • Do you have a documentation reference this is based on? – Mike Jan 25 '17 at 15:01
  • 4
    @Mike It can empirically demonstrated by writing `public sealed class AuthAttribute : System.Web.Mvc.AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) => false; }`, placing it on an `ApiController`, and setting a breakpoint in Visual Studio. Observe that the `AuthorizeCore` is never called and that the request is served where it would be rejected. – Aluan Haddad Feb 22 '17 at 08:17
  • 1
    It should be noted that MVC and Web API are **independent** frameworks, which is why these two types are not interchangeable. Specifying "the framework" implies there is only one framework, which is incorrect and misleading. – NightOwl888 Feb 22 '18 at 14:42