【发布时间】:2017-07-25 09:42:37
【问题描述】:
我有一个自托管的 Owin WebAPI。我想通过身份验证保护一些路由。大多数路由应该可以匿名访问。
我已经成功实现了 Windows-Auth,但现在我在匿名访问标有[AllowAnonymous] 的路由时得到401 - Unauthorized。如果我使用有效凭据调用该方法,一切正常。
完美的解决方案是默认允许匿名,并且仅当操作具有[Authorize] 属性时才需要凭据。
Owin 配置
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;
//..
}
}
一个示例动作
public class ValuesController : ApiController
{
[AllowAnonymous] // attribute gets ignored
[Route("Demo")]
[HttpGet]
public string Get()
{
//..
}
}
【问题讨论】:
-
刚刚为我解决了这个问题。有关详细信息,请参阅here。
-
感谢您提供的信息,它对我有用!写一个答案,我会接受的:)
标签: c# asp.net-web-api owin windows-authentication self-hosting