0

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 };
        }
    }
}
}
Milan Švec
  • 1,675
  • 17
  • 21

1 Answers1

1

What worked for me was to use the AuthenticationSchemeSelector to return the authentication scheme based on some criteria.

// Specify the authentication delegate.
listener.AuthenticationSchemeSelectorDelegate = 
    new AuthenticationSchemeSelector (AuthenticationSchemeForClient);
static AuthenticationSchemes AuthenticationSchemeForClient(HttpListenerRequest request)
{
    Console.WriteLine("Client authentication protocol selection in progress...");
    // Do not authenticate local machine requests.
    if (request.RemoteEndPoint.Address.Equals (IPAddress.Loopback))
    {
        return AuthenticationSchemes.None;
    }
    else
    {
        return AuthenticationSchemes.IntegratedWindowsAuthentication;
    }
}
Alex
  • 11
  • 2