我有一个自我托管的Owin WebAPI。我想通过身份验证来保护一些路由。大多数路线应该是匿名访问的。
我已经成功实现了Windows-Auth,但现在我在匿名访问时尝试访问标有401 - Unauthorized
的路由时获得[AllowAnonymous]
。如果我使用有效凭据调用该方法,则一切正常。
完美的解决方案是默认允许匿名,只有在操作具有[Authorize]
属性时才需要凭据。
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()
{
//..
}
}
答案 0 :(得分:3)
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.