如何修复 "The HTTP request was forbidden with client authentication scheme 'Anonymous'"

How to fix "The HTTP request was forbidden with client authentication scheme 'Anonymous'"

我在实现与 WCF 服务对话的客户端时遇到了一些问题。它是由另一家公司托管的 WCF,因此我无权访问其代码。我使用 Visual Studio 中的 Connected Service provider 工具来生成客户端代码,这样我就可以发出请求,并且在我的本地机器上一切正常。我在我们的开发环境中遇到问题,如果我尝试向客户端发出请求,我会收到以下错误:

The HTTP request was forbidden with client authentication scheme 'Anonymous'

我一直在查看由 Provider 工具生成的客户端代码(代码很多),我认为它可能与以下代码块有关。

System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
result.MaxBufferSize = int.MaxValue;
result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
result.MaxReceivedMessageSize = int.MaxValue;
result.AllowCookies = true;
result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;
return result;

result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport;

使用 HTTPS 提供安全性。该服务必须配置有 SSL 证书。 SOAP 消息作为一个整体使用 HTTPS 进行保护。客户端使用服务的 SSL 证书对服务进行身份验证。客户端身份验证通过 ClientCredentialType 进行控制。

https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.basichttpsecuritymode?view=netframework-4.8

此错误通常表示 WCF 服务器使用证书对客户端进行身份验证。当服务器和客户端之间的信任关系还没有建立时,就会出现这个错误。

一般情况下,我们需要提供客户端凭证给服务器端认证,这样才能调用服务。至于需要提供什么样的凭据,取决于服务端的绑定信息。

 BasicHttpBinding binding = new BasicHttpBinding();
            binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

即上面的错误已经表明服务器使用证书对客户端进行了身份验证。

binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

关于使用证书对客户端进行认证,可以参考下面link的详细内容
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/transport-security-with-certificate-authentication
如果有什么我可以帮忙的,请随时告诉我。

感谢所有建议。这实际上只是由我们组织内设置的防火墙规则引起的。删除后,代码将按预期工作。

这更多地与公司网络内的防火墙规则有关。

我在使用非授权代理时遇到了同样的问题,但使用 ntlm ClientCredentialType

解决了安全代理问题