Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow anonymous to ASP.NET Web API controller while rest of the application runs under windows authentication

I have an ASP.NET web application that has Windows authentication enabled. I need to write an ASP.NET Web API controller in that application that uses some of the data access logic of the application. I don't want to create a new project for the Web API alone as I need to expose just a small end point that handles a couple of requests.

The Web API clients would consume the service anonymously. To allow this, I tried using AllowAnonymous action filter on both controller as well as the actions. But, when I try hitting the API using Fiddler, the request fails with status 401 saying "401 - Unauthorized: Access is denied due to invalid credentials".

Is there a way to achieve this?

like image 721
S. Ravi Kiran Avatar asked Dec 30 '13 07:12

S. Ravi Kiran


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 bypass authorization in Web API?

If you want to allow anonymous access you can use the [AllowAnonymous] attribute. This will block access to all methods when a user is not authorized, except the GetData() method which can be called anonymously.

What option do we use in web config to enable Windows authentication for the Web application?

Select File >> New >> select ASP.NET Core Web Application, and change the authentication to Windows Authentication. We can also configure the existing application for Windows Authentication by selecting the option of WA. To configure the authentication manually, open Visual Studio project properties >> go to Debug tab.


1 Answers

The way I solved the problem, using Visual Studio 2015 and .NET 4.5.2, was to set the Web API project properties to have both Anonymous Authentication and Windows Authentication set to Enabled (note these will also have to be set in the IIS instance). Then within my controllers I decorated the methods that would require authentication with the [Authorize] attribute as well as the name of my custom authentication attribute.

This permitted the default configuration for the controller methods to accept anonymous calls and only the few special methods that required authentication had the extra decorators. I didn't have to add anything to the web.config or WebApiConfig.cs files. The Global.asax did have a call to my custom authentication static function which set global values.

like image 148
cminus Avatar answered Oct 24 '22 07:10

cminus