5

I have a self-hosted Owin WebAPI. I want to protect a few routes with authentication. The majority of the routes should be accessible anonymously. I have succesfully implemented Windows-Auth, but now I get 401 - Unauthorized when trying to access the routes marked with [AllowAnonymous] when accessing them anonymously. If I call the method with valid credentials all works fine.

The perfect solution would be to allow anonymous by default and only require credentials when the action has the [Authorize] attribute.

Owin config

public void Configuration(IAppBuilder appBuilder)
{
    // Enable Windows Authentification
    HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
    listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

    HttpConfiguration config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();

    appBuilder.Use(typeof(WinAuthMiddleware));
    appBuilder.UseWebApi(config);
}

WinAuth OwinMiddleware

public class WinAuthMiddleware : OwinMiddleware
{
    public WinAuthMiddleware(OwinMiddleware next) : base(next) {}
    public async override Task Invoke(IOwinContext context)
    {
        WindowsPrincipal user = context.Request.User as WindowsPrincipal;
        //..
    }
}

An example Action

public class ValuesController : ApiController
{      
    [AllowAnonymous] // attribute gets ignored
    [Route("Demo")]
    [HttpGet]
    public string Get()
    {
        //..
    }
}
Kai
  • 135
  • 2
  • 7
  • Just had this problem solved for me.. see [here](https://stackoverflow.com/questions/45485454/owin-self-host-with-windows-authentication-allowanonymous-not-working/45485916#45485916) for details. – user3566056 Aug 04 '17 at 07:57
  • Thanks for the information, it worked for me! Write an answer and I'll accept it :) – Kai Aug 04 '17 at 11:46

1 Answers1

4

Your issue is that you configured the HttpListener to support only Windows authentication. This is similar to configuring an IIS site with just Windows Authentication: every request to the site has to go through windows Authentication.

To selectively activate authentication, you need to allow both Windows authentication and anonymous authentication by changing your configuration to this

public void Configuration(IAppBuilder appBuilder)
{
    // Enable Windows Authentification and Anonymous authentication
    HttpListener listener = 
    (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
    listener.AuthenticationSchemes = 
    AuthenticationSchemes.IntegratedWindowsAuthentication | 
    AuthenticationSchemes.Anonymous;

    HttpConfiguration config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();

    appBuilder.Use(typeof(WinAuthMiddleware));
    appBuilder.UseWebApi(config);
}

Do that and your standard [Authorize] and [AllowAnymous] tags start working as expected.

user3566056
  • 224
  • 1
  • 12