如何将X509证书从客户端发送到服务器WebSocketSharp C#

时间:2018-10-29 11:09:31

标签: c# websocket websocket-sharp

我正在尝试使用WebSocketSharp在客户端/服务器之间发送和验证SSL证书

服务器端

wss = new WebSocketServer(IPAddress.Parse("127.0.0.1"), 6070, true);
string _certificatePath = Path.GetDirectoryName(typeof(WSS_Server).Assembly.Location) + "\\cert\\public_privatekey.pfx";
wss.SslConfiguration.ServerCertificate = new X509Certificate2(_certificatePath, "mypass");
wss.SslConfiguration.ClientCertificateRequired = false; // true;
wss.SslConfiguration.CheckCertificateRevocation = false; // true;
wss.SslConfiguration.ClientCertificateValidationCallback = RemoteCertificateValidationCallback;

wss.AddWebSocketService<MyRemoteService>(
"/myservice",
() => new MyRemoteService()
{
    OriginValidator = val =>
    {
        // Check the value of the Origin header, and return true if valid.
        return true;
    },
    CookiesValidator = (req, res) =>
    {
        return true; // If valid.
    }

});

客户端

var ws = new WebSocket("wss://127.0.0.1:6070/myservice/");
string _certificatePath = "\\cert\\public_privatekey.pfx";
X509Certificate2 x509 = new X509Certificate2(_certificatePath, "mypass");
X509CertificateCollection xcol = new X509CertificateCollection();
xcol.Add(x509);

ws.SslConfiguration = new WebSocketSharp.Net.ClientSslConfiguration("127.0.0.1", xcol, System.Security.Authentication.SslProtocols.Default, false);
//ws.SslConfiguration.ClientCertificates = new X509CertificateCollection();
//ws.SslConfiguration.ClientCertificates.Add(x509);

ws.OnOpen += Ws_OnOpen;
ws.OnMessage += Ws_OnMessage;
ws.OnError += Ws_OnError;
ws.OnClose += Ws_OnClose;
ws.Connect();

在服务器端,RemoteCertificateValidationCallback 证书始终为 null

就像客户端从不发送证书。

任何想法如何解决?

3 个答案:

答案 0 :(得分:0)

您随时可以在WebSocketSharp中设置或获取包含客户端证书的集合。

要完成此操作,您可以将X509Certificate2对象添加到ClientCertificates中。

您在这里:

var ws = new WebSocket("wss://127.0.0.1:6070/myservice/");
string _certificatePath = "\\cert\\public_privatekey.pfx";
X509Certificate2 x509 = new X509Certificate2(_certificatePath, "mypass");    
ws.SslConfiguration.ClientCertificates.Add(x509);
ws.Connect();

然后,您可以在服务器端验证此证书。希望这将是您的问题的答案。

答案 1 :(得分:0)

我遇到了同样的问题

X509Certificate2 cert = new X509Certificate2(fileName, "", X509KeyStorageFlags.MachineKeySet);
ws.SslConfiguration.ClientCertificates = new X509CertificateCollection() { };
ws.SslConfiguration.ClientCertificates.Add(cert);

答案 2 :(得分:0)

这里没有答案对我有用。为了使其正常工作,我需要将SslConfiguration.ClientCertificateSelectionCallback设置为适当的值,例如:

X509Certificate2 cert = new X509Certificate2(fileName, "", X509KeyStorageFlags.MachineKeySet);
ws.SslConfiguration.ClientCertificateSelectionCallback =
            (sender,targethost,localCertificates, remoteCertificate,acceptableIssuers) =>
            {
                return cert;
            };

实际上,WebsocketSharp源代码中的documentation of SslConfiguration.ClientCertificateSelectionCallback明确指出:

  

获取或设置用于选择要提供给的证书的回调   服务器。 如果回调返回,则不提供证书   空。 [...] 默认值是调用 a   仅返回null的方法

因此,如果您未在此回调中显式提供客户端证书,则不会发送证书。