WCF中基于证书的身份验证

时间:2017-09-15 15:39:55

标签: wcf certificate

我正在尝试使用msdn示例https://msdn.microsoft.com/en-us/library/ms731074(v=vs.90).aspx

了解基于证书的身份验证

这是服务器代码:

WSHttpBinding binding = new WSHttpBinding(); 
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

// Create the URI for the endpoint. 
Uri httpUri = new Uri("https://localhost/Calculator");

// Create the service and add an endpoint. 
ServiceHost myServiceHost = new ServiceHost(typeof(ServiceModel.Calculator), httpUri); 
myServiceHost.AddServiceEndpoint(typeof(ServiceModel.ICalculator), binding, "");

// Open the service. 
myServiceHost.Open();

Console.WriteLine("Listening..."); 
Console.ReadLine();

// Close the service. 
myServiceHost.Close();

这是我写的客户端代码:

ChannelFactory<ICalculator> factory = null;

WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

EndpointAddress address = new EndpointAddress("https://localhost/Calculator");

factory = new ChannelFactory<ICalculator>(binding, address);

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "sroger");

ICalculator channel = factory.CreateChannel();

int y = channel.add(9, 8);

我收到以下异常:

  

mscorlib.dll中发生未处理的“System.ServiceModel.CommunicationException”类型异常

     

其他信息:向https://localhost/Calculator发出HTTP请求时发生错误。这可能是由于在HTTPS情况下未使用HTTP.SYS正确配置服务器证书。这也可能是由于客户端和服务器之间的安全绑定不匹配造成的。

我在同一台机器上运行客户端和服务器。 “sroger”是我当前用户\个人\证书中的证书,对应于我的机器名称。 不知道该怎么办。有什么想法吗? 在服务器代码中,证书服务器使用什么?

由于

Gulumal。

1 个答案:

答案 0 :(得分:0)

您使用的

https://msdn.microsoft.com/en-us/library/ms731074(v=vs.90).aspx示例不完整。 使用https wcf服务需要有效的服务器证书才能工作,在您的情况下,需要客户端和服务器证书。 这是因为客户端和服务器都需要在HTTPS连接中相互信任。

要开始使用,请阅读https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/message-security-with-mutual-certificates,这是一个更完整的示例,其中包括指定证书来验证服务。

对于通过https工作的托管WCF库,您需要按顺序执行以下操作:

  1. 使用X.509证书配置端口(已经过 回答说 webHttpBinding with certificate
  2. 从您的服务器,为您的公用名创建证书申请 服务器完全限定域名,或至少包括服务器完全限定域名的DNS subjectAltName。 (有不同的方法,你可能已经知道这一点 虽然)
  3. 在您的服务器上颁发证书并安装证书
  4. 从托管WCF的应用程序的程序集文件中获取应用程序ID 库(即[汇编: Guid(&#34; 5870aeed-caca-4734-8b09-5c0615402bcf&#34;)])拿到证书 查看证书属性的指纹。
  5. 作为管理员,请打开 CMD并运行此命令将X.509证书绑定到使用的端口 由您在服务器上的应用

    netsh http add sslcert ipport = 0.0.0.0:443 certhash = appid = {} certstorename = MY

    netsh http add iplisten ipaddress = 0.0.0.0:443

  6. 将此添加到您的服务器代码:

    myServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySerialNumber, "<certificate thumbprint>");
    

    在您的客户端代码中,通过完全限定的域名引用您的服务器地址,该证书被指定为证书公用名称或主题Alt名称