【问题标题】:Owin Self-Host WebApi Windows Authentication and AnonymousOwin 自托管 WebApi Windows 身份验证和匿名
【发布时间】: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


【解决方案1】:

您的问题是您将 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] 标签开始按预期工作。

【讨论】:

    猜你喜欢
    • 2014-02-20
    • 2013-07-01
    • 2019-09-16
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2014-08-19
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多