在WCF和Windows身份验证中处理CORS

Obl*_*obl 6 c# wcf windows-authentication cors angular

我已经实现了一个自托管的WCF Rest服务和一个相应的Angular CLI Client.我遇到了麻烦CORS,但是当我HttpClientCredentialType.None设置在内部时,我能够解决它们WebHttpBinding.

问题是,我需要使用HttpClientCredentialType.Windows,因为我必须知道使用该系统的Windows用户的身份.
这是使用的绑定:

new WebHttpBinding
{
    MaxBufferSize = int.MaxValue,
    MaxBufferPoolSize = 524288,
    MaxReceivedMessageSize = int.MaxValue,                
    OpenTimeout = TimeSpan.FromMinutes(1),
    SendTimeout = TimeSpan.FromMinutes(1),
    ReceiveTimeout = TimeSpan.FromMinutes(10),
    CloseTimeout = TimeSpan.FromMinutes(1),
    ReaderQuotas =
    {
        MaxStringContentLength = int.MaxValue,
        MaxArrayLength = int.MaxValue,
        MaxDepth = int.MaxValue,
        MaxNameTableCharCount = int.MaxValue
    },
    Security =
    {
        Mode = WebHttpSecurityMode.Transport,
        Transport = { ClientCredentialType = HttpClientCredentialType.Windows }
        //Transport = { ClientCredentialType = HttpClientCredentialType.None}
    }
};
Run Code Online (Sandbox Code Playgroud)

但现在CORS-Options使用HttpStatus拒绝调用401 Unauthorized,因为它中没有身份验证头.因此,整个电话被拒绝(理论上是正确的).

当然我已经添加了所有必要的标题.如上所述,它适用于None身份验证.

WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Id, Origin, Authorization");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Credentials", "true");
Run Code Online (Sandbox Code Playgroud)

所以我看到了解决问题的三种可能性.

  1. Angular以某种方式在我的客户端获取CORS-Options调用以通过我的Windows凭据.
  2. 获取WCF服务以忽略CORS-Options调用中的身份验证.
  3. 将授权设置回"无"并以其他方式传递我的Windows凭据(不强制用户输入其凭据).

它甚至还使用Windows身份验证的作品,当我使用--disable-web-securityChrome Browser.但对我来说,这不是生产系统的解决方案.

也许有人对我的问题有任何想法甚至解决方案.

Bar*_*r J 0

这里的选项是使用Microsoft.AspNet.WebApi.Cors

我使用 Web Api 遇到了这个问题,并发现这个解决方案(nuget 包)也适用于 WCF。

你需要在你的类之上使用这个装饰器:

[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
Run Code Online (Sandbox Code Playgroud)

然后在你的方法之上添加装饰器:

[AcceptVerbs("POST")]
Run Code Online (Sandbox Code Playgroud)

这将忽略飞行前请求,仅发送您的实际请求。

编辑

进一步查看您的代码后,我理解了这个问题:您需要一个额外的参数:

var cors = new EnableCorsAttribute("http://IP:PORT", "*", "*") { SupportsCredentials = true };
config.EnableCors(cors); 
Run Code Online (Sandbox Code Playgroud)

ASP.NET 论坛上有一篇很棒的帖子可以帮助解决您的情况。

按照要求

这是wcf 中的解决方法HttpConfiguration