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

时间:2012-01-06 09:28:07

标签: 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>

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

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

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

由于

1 个答案:

答案 0 :(得分: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();

这取代了我的配置。