C#-Owin自托管WebApi Windows身份验证和匿名

我有一个自托管的Owin WebAPI.我想通过身份验证来保护一些路由.大多数路线应匿名访问.我已经成功实现了Windows-Auth,但是现在当我匿名访问它们时,尝试访问带有[AllowAnonymous]标记的路由时得到401-未经授权.如果我使...

我有一个自托管的Owin WebAPI.我想通过身份验证来保护一些路由.大多数路线应匿名访问.
我已经成功实现了Windows-Auth,但是现在当我匿名访问它们时,尝试访问带有[AllowAnonymous]标记的路由时得到401-未经授权.如果我使用有效的凭据调用该方法,则一切正常.

完美的解决方案是默认情况下允许匿名,并且仅在操作具有[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 Owin中间件

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()
    {
        //..
    }
}

解决方法:

您的问题是您将HttpListener配置为仅支持Windows身份验证.这类似于仅通过Windows身份验证配置IIS站点:对该站点的每个请求都必须通过Windows身份验证.

要有选择地激活身份验证,您需要通过将配置更改为此来允许Windows身份验证和匿名身份验证

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);
}

这样做,您的标准[Authorize]和[AllowAnymous]标签就会按预期开始工作.

本文标题为:C#-Owin自托管WebApi Windows身份验证和匿名

基础教程推荐