I am trying to develop selfhosted OWIN WebApp. Everything OK, until I tried to integrate Windows (NTLM) authentication. Windows authentication works fine if only IntegratedWindowsAuthentication is activated. But I need some of the requests to remain anonymous.
I already found that I have to enable both authentication methods:
AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous
But in such case I get "Authorization has been denied for this request". Tested with Chrome as client (http://localhost:9009/api/test).
Please help.
OWIN startup class:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
// Enable Windows & Anonymous Authentification
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes =
AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous;
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
appBuilder.UseWebApi(config);
}
}
Main program:
static void Main()
{
string baseAddress = "http://localhost:9009/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("Server ready");
Console.ReadLine();
}
}
Test controller:
using System.Collections.Generic;
using System.Security.Principal;
using System.Web.Http;
namespace SelfhostNTAuth
{
public class TestController : ApiController
{
[Authorize]
public IEnumerable<string> Get()
{
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;
if (user == null)
{
return new string[] { "unauthorized"};
}
else
{
return new string[] { user.Identity.AuthenticationType, user.Identity.Name };
}
}
}
}