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?
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.
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.
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.
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.
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