动态设置x509以用于WCF双工命令

本文关键字:命令 WCF 用于 设置 x509 动态 | 更新日期: 2023-09-27 18:19:40

我正在使用x509证书连接到双工WCF服务,在客户端配置文件中指定证书详细信息,如下所示:

<behaviors>
  <endpointBehaviors>
    <behavior name="ScannerManagerBehavior">
      <clientCredentials>
        <clientCertificate findValue="ClientName" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" />
        <serviceCertificate>
          <authentication certificateValidationMode="PeerTrust" />
        </serviceCertificate>
      </clientCredentials>
    </behavior>
  </endpointBehaviors>
</behaviors>

然后连接到WCF服务的代码:

DuplexChannelFactory<IScannerManager> _smFactory 
= new DuplexChannelFactory<IScannerManager>(instanceContext, nameOfEndPoint);
var _commsChannel = _smFactory.CreateChannel();

我现在需要在代码中指定将以程序方式使用的客户端证书名称。我有可能那样做吗?我可以看到我可以创建自己的x509Certificate2类,但我不确定如何更改/设置findValue="clientName"位。。。

感谢

动态设置x509以用于WCF双工命令

好的,所以使用wal的有用评论(谢谢!)我设法让它工作起来。我遇到的问题是,如果你要在代码中动态设置客户端配置的任何部分,你就不能使用任何.config——你必须在代码中定义它。所以这几乎是要么全有要么全无。至少那是我的经历。

所以,对我来说,我必须这样做:

 var binding = new NetTcpBinding();
 binding.Security.Mode = SecurityMode.Transport;
 binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
 binding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;
 binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
 var identity = new DnsEndpointIdentity("localhost");
 Uri uri = new Uri("tcp:URI goes here");
 var address = new EndpointAddress(uri, identity, new AddressHeaderCollection());
 _smFactory = new DuplexChannelFactory<IScannerManager>(instanceContext, binding, address);
 _smFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "CustomCertificateNameHere");
 _commsChannel = _smFactory.CreateChannel();

它取代了我的配置。