我所有的代码都是.Net 4.0。
我有使用证书+用户名/密码身份验证的 wcf 服务。在我的服务中,我使用了自签名证书,因此加载到客户端的公钥应该去Trusted People
存储。我知道这一点。
我使用通道工厂打开连接。我的代码如下所示:
public static ChannelFactory<T> CreateMyServiceClientChannel<T>(string serviceUrl, string serviceUsername, string servicePassword)
{
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
binding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509Certificate2 clientCertificate = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(cert => cert.Subject == "CN=MyServicesCert");
store.Close();
// Instantiate the EndPointAddress using the Service URL, endpoint identity
Uri baseAddress = new Uri(serviceUrl);
EndpointIdentity epi = EndpointIdentity.CreateX509CertificateIdentity(clientCertificate);
EndpointAddress endpoint = new EndpointAddress(baseAddress, epi);
// Create the Channel Factory instance using binding and end point variables.
ChannelFactory<T> channelFactory = new ChannelFactory<T>(binding, endpoint);
// set credentials
channelFactory.Credentials.UserName.UserName = serviceUsername;
channelFactory.Credentials.UserName.Password = servicePassword;
channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
// Return the channel factory
return channelFactory;
}
这里的问题是倒数第二个陈述:
channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
在我的 Windows 7 机器中,我不必包含它,我可以与服务正常通信。但是在 Windows XP 机器中,如果我不包含它,我会遇到异常
System.ServiceModel.Security.SecurityNegotiationException:与目标 'net.tcp://my-server:20800/my-service.svc' 的 SOAP 安全协商 'net.tcp://my-server:20800/my-service。 svc' 失败。有关更多详细信息,请参阅内部异常。---> System.IdentityModel.Tokens.SecurityTokenValidationException:X.509 证书 CN=MyServicesCert 链构建失败。使用的证书具有无法验证的信任链。更换证书或更改 certificateValidationMode。已处理的证书链,但在信任提供者不信任的根证书中终止。
所以看起来 .net 在 Windows 7 和 XP 之间的行为不同,那是怎么回事?