首页 > 解决方案 > 使用 WCF 使用受基本身份验证和证书保护的 SOAP 服务

问题描述

我正在尝试在 Visual Studio 2019 中构建一个客户端,它将使用一个使用 id/pass 和证书保护的 SOAP 服务。

我通过导入 WSDL 创建了一个 SoapUI 项目,然后将项目上的 ws-security 设置配置为具有传出签名并导入具有我要使用的证书的密钥库。最后,我在使用 Basic 的请求上设置了身份验证,设置了 id/pass 并在 Outgoing WSS 下拉列表中选择了我的传出签名。完成所有这些之后,我可以使用 Soap UI 完美地调用该服务。

在 Visual Studio 中,我创建了一个新的控制台项目,使用相同的 WSDL 添加了一个连接的服务引用,现在我正在尝试编写代码。我尝试通过执行设置凭据

System.ServiceModel.BasicHttpsBinding myBinding = new System.ServiceModel.BasicHttpsBinding();
System.ServiceModel.EndpointAddress myAddress = new System.ServiceModel.EndpointAddress("url");
ServiceReference1.CaseTypeClient myClient = new ServiceReference1.CaseTypeClient(myBinding, myAddress);
myClient.ClientCredentials.UserName.UserName = "ID";
myClient.ClientCredentials.UserName.Password = "Pass";
System.Security.Cryptography.X509Certificates.X509Certificate2 myCert = new System.Security.Cryptography.X509Certificates.X509Certificate2("CertFileName", "CertPass");
myClient.ClientCredentials.ClientCertificate.Certificate = myCert;

但是,当我调用该方法时,我会从服务中返回一个 soapfault,说“XmlException:限定名称'wsse:FailedAuthentication' 中使用的未绑定前缀”。

做我想要完成的事情的正确方法是什么?

标签: c#.netwcfws-securitywsse

解决方案


如果是基于客户端代理调用服务,可以根据配置文件中自动生成的绑定配置和认证方式提供相应的凭证。
我想知道什么是认证模式。为什么我们在设置证书后需要提供 id/pass 证书?通信期间是否有网络代理?
另外,为了保证证书可以被WCF服务访问,我们通常会在本地证书存储中安装客户端证书,并添加Everyone账户证书的私钥管理组,然后提供证书,声明如下.

    ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
                client.ClientCredentials.Windows.ClientCredential.UserName = "administrator";
                client.ClientCredentials.Windows.ClientCredential.Password = "123456";
client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "9b8db0dfe615458ace0ae9e89fcb983c5d16f633");

如果项目基于Basic认证,我们只需要设置http头,使用Base64编码的用户名和密码。

授权:基本 YWRtaW5pc3RyYXRvcjphYmNkMTIzNCE=

如果有什么我可以帮助的,请随时告诉我


推荐阅读