WCF客户端HTTPS请求异常

时间:2020-01-14 14:15:54

标签: c# .net wcf soap client

我正在为.Net Core 2.1中的SOAP HTTPS Web服务构建WCF客户端。

服务提供商已提供了.key和.cert文件,我已使用openssl将其转换为.p12文件。通过将其添加到密钥库中,我可以通过SoapUI将请求成功发送到Web服务(除了证书之外,不需要其他身份验证)。

要在.Net Core中执行相同的操作,我已通过Visual Studio中的WCF向导在项目中添加了连接服务。该服务基于提供的服务合同(WSDL文件)。然后,我已经在本地PC上安装了.p12证书,并且正在使用以下代码进行请求。 “ MyService”是已连接的服务。

var binding = new BasicHttpsBinding();
binding.Security.Mode = BasicHttpsSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;

var endpoint = new EndpointAddress("https://x.x.x.x:8300/MyService.asmx");
var channelFactory = new ChannelFactory<MyService>(binding, endpoint);    
channelFactory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
channelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
        {
            CertificateValidationMode = X509CertificateValidationMode.None,                
            RevocationMode = X509RevocationMode.NoCheck,
            TrustedStoreLocation = StoreLocation.LocalMachine
        };

channelFactory.Credentials.ClientCertificate.SetCertificate(
        StoreLocation.CurrentUser,
        StoreName.My,
        X509FindType.FindByIssuerName,
        "xxxxxxxxxxxxxxxxxxxxxxxxxx");  

var service = channelFactory.CreateChannel(); 


ExecuteResponse response = service.Execute(new ExecuteRequest());

运行此代码时,出现以下错误:

System.ServiceModel.Security.MessageSecurityException:'HTTP请求未经客户端身份验证方案'Anonymous'授权。从服务器收到的身份验证标头是“协商”。

奇怪的是,如果我使用HttpClientHandler,我就可以发出请求,这告诉我两个实现的基础结构之间一定不匹配。 有谁知道我该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

该证书可能仅用于在客户端和服务器端之间建立信任关系。
为了成功调用该服务,我们应该使客户端和服务器端之间的绑定类型保持一致。因此,我想通过添加服务参考来了解自动生成的客户端配置,请发布位于客户端项目System.servicemodel中的appconfig部分。
enter image description here
如果服务器使用证书对客户端进行身份验证,则该错误通常表示客户端和服务器端之间尚未建立信任关系。
在客户端,我们应该在LocalCA中安装服务器证书。在服务器端,我们应该将客户端证书安装在LocalCA证书存储中。
随时让我知道问题是否仍然存在。