ASP.NET Web API Authorization with AuthorizeAttribute

Double check that you are using the System.Web.Http.AuthorizeAttribute and not the System.Web.Mvc.AuthorizeAttribute. This bit me before. I know the WebAPI team is trying to pull everything together so that it is familiar to MVC users, but I think somethings are needlessly confusing.


Set your authentication mode to None:

<authentication mode="None" />

None Specifies no authentication. Your application expects only anonymous users or the application provides its own authentication.

http://msdn.microsoft.com/en-us/library/532aee0e.aspx

Of course then you have to provide some sort of authentication via headers or tokens or something. You could also specify Windows and use the built in auth via headers.

If this site is mixed between API and actual pages that do need the Forms setting, then you will need to write your own handling.

All the attribute does is return an HttpUnauthorizedResult instance, the redirection is done outside of the attribute, so its not the problem, its your authentication provider.


Finally, I've found a solution at: ASP.NET MVC 4 WebAPI authorization

This article shows how you can fix this issue.


You are being redirected to login page because forms authentication module does this automatically. To get rid of that behavior disable forms authentication as suggested by Paul. If you want to use more REST friendly approach you should consider implementing HTTP authorization support. Take a look at this blog post http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/


ASP.NET 5 Introduced the new Microsoft.AspNet.Authorization System which can secure both MVC and Web API controllers.

For more see my related answer here.

Update:

At that time 2 years ago it was Microsoft.AspNetCore.Authorization.

As @Chris Haines pointed out. now it resides on Microsoft.AspNetCore.Authorization.

From .NET core 1.0 to 2.0 many namespaces have been moved i think. And spread functionality between .net classic and core was obscure. That's why Microsoft introduced the .net standard.

.net standard