Reputation: 155
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.
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);
}
public class WinAuthMiddleware : OwinMiddleware
{
public WinAuthMiddleware(OwinMiddleware next) : base(next) {}
public async override Task Invoke(IOwinContext context)
{
WindowsPrincipal user = context.Request.User as WindowsPrincipal;
//..
}
}
public class ValuesController : ApiController
{
[AllowAnonymous] // attribute gets ignored
[Route("Demo")]
[HttpGet]
public string Get()
{
//..
}
}
Upvotes: 6
Views: 4586
Reputation: 244
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.
Upvotes: 5