代码之家  ›  专栏  ›  技术社区  ›  Gulumal

WCF中基于证书的身份验证

  •  0
  • Gulumal  · 技术社区  · 8 年前

    我正在尝试使用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);
    

    我遇到以下例外情况:

    “System”类型的未处理异常。服务模型。mscorlib中出现“CommunicationException”。dll

    https://localhost/Calculator . 这可能是因为服务器证书没有正确配置HTTP。HTTPS情况下的SYS。这也可能是由于客户端和服务器之间的安全绑定不匹配造成的。

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

    古鲁马尔。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Iggy Zofrin    8 年前

    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. 在中回答 webHttpBinding with certificate )
    2. 从您的服务器上,为您的公用名创建证书请求 (有不同的方法可以做到这一点,你可能已经知道了
    3. 在服务器上颁发证书并安装证书
    4. 从承载WCF的应用程序的程序集文件中获取应用程序id Guid(“5870aeed-caca-4734-8b09-5c0615402bcf”)])获取证书
    5. 作为管理员,打开 通过服务器上的应用程序

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

      netsh http add iplisten ipaddress=0.0.0.0:443

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

    推荐文章