c# - OWIN 托管的 web api : using windows authentication and allow anonymous access

标签 c# asp.net-web-api owin

我有一个使用 OWIN 自托管的 WebApi 项目。

我想对某些 Controller 的操作启用 Windows 身份验证,但允许匿名调用其他操作。

因此,根据我在网上找到的一些示例,我在我的 Statrup 类中设置了我的 WebApi:

public void Configuration(IAppBuilder appBuilder)
{
    HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
    listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous; //Allow both WinAuth and anonymous auth

    //setup routes and other stuff
    //...

    //Confirm configuration
    appBuilder.UseWebApi(config);
}

然后,在我的 Controller 中,我创建了两个 Action :

[HttpGet]
[Authorize]
public HttpResponseMessage ProtectedAction()
{
    //do stuff...
}

[HttpGet]
[AllowAnonymous]
public HttpResponseMessage PublicAction()
{
    //do stuff...
}

然而,这是行不通的。 调用标记为 AllowAnonymous 的操作按预期工作,但调用标记为 Authorize 的操作总是返回 401 错误和以下消息:

{
    "Message": "Authorization has been denied for this request."
}

即使调用者支持 windows 身份验证,在浏览器(Chrome 和 Edge)和 Postman 上测试。

我在这里错过了什么?

最佳答案

好吧,我在另一个问题中找到了解决这个问题的方法。 您可以在运行时通过设置 AuthenticationSchemeSelector 方法为每个请求选择身份验证模式,而不是指定多个身份验证模式(这不起作用):

public void Configuration(IAppBuilder app)
{
    HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
            listener.AuthenticationSchemeSelectorDelegate = new 
    AuthenticationSchemeSelector(GetAuthenticationScheme);
}

private AuthenticationSchemes GetAuthenticationScheme(HttpListenerRequest httpRequest)
{
    if(/* some logic... */){
        return AuthenticationSchemes.Anonymous;                    
    }
    else{
        return AuthenticationSchemes.IntegratedWindowsAuthentication;
    }
}

虽然不理想(您必须手动检查请求 URL 或请求的其他一些参数来决定使用哪种方法)但它有效。

关于c# - OWIN 托管的 web api : using windows authentication and allow anonymous access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868244/

相关文章:

c# - 如何获得强类型 MVC View 以回发它传递的模型实例?

jquery - webapi mvc4 所需的注释对于整数属性失败,但对于字符串有效

c# - ASP.NET Identity Token Methods 接受所有 HTTP 方法

c# - 在MVC项目中使用微软账号认证时如何获取用户邮箱?

c# - 在没有空格键的情况下计算字符串中的字母

c# - ASP.NET Core Razor 页面值不能为空

c# - ASP.NET ActionResult 对本地主机和托管的 Azure Web 服务提供不同的响应

asp.net-web-api - 为什么当我发布到服务器时,NSwag/Swagger 方案仅设置为 HTTP,但在我的本地计算机上却设置为 HTTPS?

azure - 在 Azure 上发布 WebApi 后出现 "unsupported_grant_type"

c# - 序列包含多个元素 Microsoft.Owin.Security.AuthenticationManager