动态设置x509以用于WCF双工通信

Mat*_*rts 5 c# wcf x509certificate

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

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

DuplexChannelFactory<IScannerManager> _smFactory 
= new DuplexChannelFactory<IScannerManager>(instanceContext, nameOfEndPoint);
var _commsChannel = _smFactory.CreateChannel();
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Mat*_*rts 2

好的,所以使用 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();
Run Code Online (Sandbox Code Playgroud)

这取代了我的配置。