[英]WCF over TLS under Mono
我試圖通過TLS連接使WCF通信工作。 我在Ubuntu 18.04上使用Mono 5.20.1.19,雖然我希望解決方案也適用於Windows。
考慮一個這樣的基本界面:
IExample.cs:
using System;
using System.ServiceModel;
namespace Example
{
[ServiceContract]
public interface IExample
{
[OperationContract]
string Greet();
}
}
我有一個服務器,為接口的實現設置ServiceHost:
Server.cs:
using System;
using System.Net;
using System.Net.Security;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Security.Cryptography.X509Certificates;
namespace Example
{
public class ExampleImpl : IExample
{
public string Greet()
{
Console.WriteLine("Greet() called");
return "Hello!";
}
}
public static class Program
{
public static void Main(string[] args)
{
using(var host = new ServiceHost(typeof(ExampleImpl), new Uri("net.tcp://localhost:5555"))){
var binding = new NetTcpBinding(SecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
binding.Security.Transport.ProtectionLevel = ProtectionLevel.EncryptAndSign;
host.Credentials.ServiceCertificate.SetCertificate(
StoreLocation.CurrentUser,
StoreName.My,
X509FindType.FindBySubjectName,
"server");
host.AddServiceEndpoint(typeof(IExample), binding, "Example");
host.Open();
Console.WriteLine("listening at :5555");
Console.WriteLine("Press Enter to end the program");
Console.ReadLine();
}
}
}
}
請注意,為NetTcpBinding指定了SecurityMode.Transport
,為客戶端憑據類型指定了TcpClientCredentialType.Certificate
。 除了證書的私鑰之外,我還指定了我安裝到My
certificate store的證書。
現在客戶:
Client.cs:
using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace Example
{
public static class Program
{
public static void Main(string[] args)
{
var binding = new NetTcpBinding(SecurityMode.None);
var factory = new ChannelFactory<IExample>(binding, new EndpointAddress("net.tcp://localhost:5555/Example"));
var obj = factory.CreateChannel();
Console.WriteLine(obj.Greet());
}
}
}
請注意,在客戶端中,NetTcpBinding的安全模式設置為None
,並且未指定客戶端證書。
我們可以構建這兩個程序:
$ csc Server.cs IExample.cs
Microsoft (R) Visual C# Compiler version 2.8.2.62916 (2ad4aabc)
Copyright (C) Microsoft Corporation. All rights reserved.
$ csc Client.cs IExample.cs
Microsoft (R) Visual C# Compiler version 2.8.2.62916 (2ad4aabc)
Copyright (C) Microsoft Corporation. All rights reserved.
現在,如果我們運行Server.exe,保持打開狀態,然后在另一個會話中運行Client.exe,服務器將打印出Greet() called
的消息,而客戶端則打印Hello!
。
我的困惑是連接成功的原因。 我希望由於服務器的綁定設置為Transport
,那么它應該需要TLS連接; 但是,似乎沒有使用TLS,因為沒有指定客戶端證書。
如何更改代碼的服務器部分以要求TLS連接?
首先,我無法重現您的問題,當我在本地調用服務時發生以下錯誤。
然后,NetTcpBinding可以使用Windows憑據或證書來確保傳輸層安全性。
請參閱我之前回復的帖子。
https://social.msdn.microsoft.com/Forums/vstudio/en-US/7b300a92-8533-4afe-9e8b-3f38138dd23b/ssltsl-with-nettcpbinding?forum=wcf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.