Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API Authorization with AuthorizeAttribute

Using the new ASP.NET Web API beta. I can not seem to get the suggested method of authenticating users, to work. Where the suggested approach seems to be, to add the [Authorize] filter to the API controllers. For example:

[Authorize]  public IEnumerable<Item> Get() {     return itemsService.GetItems(); } 

This does not work as intended though. When requesting the resource, you get redirected to a login form. Which is not very suitable for a RESTful webapi.

How should I proceed with this? Will it work differently in future versions?, or should I fall back to implementing my own action filter?

like image 713
Morgan Bengtsson Avatar asked Mar 02 '12 10:03

Morgan Bengtsson


People also ask

How will you implement authentication and authorization in ASP.NET Web API?

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

How do I add authentication to Web API?

In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.


1 Answers

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.

like image 86
AlexGad Avatar answered Sep 29 '22 11:09

AlexGad