Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

secure connection example not working #148

Closed
daxfrancis opened this issue Sep 15, 2015 · 15 comments
Closed

secure connection example not working #148

daxfrancis opened this issue Sep 15, 2015 · 15 comments

Comments

@daxfrancis
Copy link

Can you please give a good example for secure web socket server using fleck.
Currently I have used the following code but not working

C# :

// Store the subscribed clients.
var clients = new List();

        // Initialize the WebSocket server connection.
        var server = new WebSocketServer("wss://localhost:9393");
        server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(Application.StartupPath + "\\servercert.pfx", "pwd");
        server.Start(socket =>
        {
            socket.OnOpen = () =>
            {
                // Add the incoming connection to our list.
                clients.Add(socket);
            };

            socket.OnClose = () =>
            {
                // Remove the disconnected client from the list.
                clients.Remove(socket);
            };

            socket.OnMessage = message =>
            {
                // Client sends a JSON-encoded string message.

                // Send the message as-is and the client will decode it appropriately.


                foreach (var client in clients)
                {
                    client.Send(message);
                }
            };

            socket.OnBinary = message =>
            {
                // Client sends a binary message (we accept images).

                // Send this file to everyone.
                foreach (var client in clients)
                {
                    client.Send(message);
                }
            };
        });

Client Side Javascript Code:

<script type="text/javascript"> /** \* Executed when the page has finished loading. */ window.onload = function () { ``` // Create a reference for the required DOM elements. // var nameView = document.getElementById("name-view"); // var textView = document.getElementById("text-view"); var buttonSend = document.getElementById("buttonSend"); // var buttonStop = document.getElementById("stop-button"); var label = document.getElementById("status-label"); // var chatArea = document.getElementById("chat-area"); var image = document.getElementById("img_Scannedimage"); var imageshow = document.getElementById("Imageshow"); // Connect to the WebSocket server! var socket = new WebSocket("wss://127.0.0.1:9393"); //socket.binaryType = "arraybuffer"; /** * WebSocket onopen event. */ socket.onopen = function (event) { label.innerHTML = "Connection open"; $("#div_downaloadJFWebTWAINService").hide(); $("#div_imageshowhide").show(); } /** * WebSocket onmessage event. */ socket.onmessage = function (event) { if (typeof event.data === "string") { // Create a JSON object. var jsonObject = JSON.parse(event.data); // Extract the values for each key. var userName = jsonObject.name; var userMessage = jsonObject.message; alert(event.data); // Display message. // chatArea.innerHTML = chatArea.innerHTML + "

" + userName + " says: " + userMessage + "" + "

"; // Scroll to bottom. // chatArea.scrollTop = chatArea.scrollHeight; } else if (event.data instanceof Blob) { // Get the raw data and create an image element. var blob = event.data; window.URL = window.URL || window.webkitURL; var source = window.URL.createObjectURL(blob); image.src = source; image.alt = "Image generated from blob"; imageshow.src = source; imageshow.alt = "Scanned Copy"; App.unblockUI($('#div_imageshow')); // document.body.appendChild(image); } else if (event.data === "ArrayBuffer") { alert(event.data); } } /** * WebSocket onclose event. */ socket.onclose = function (event) { var code = event.code; var reason = event.reason; var wasClean = event.wasClean; if (wasClean) { label.innerHTML = "Connection closed normally."; } else { label.innerHTML = "Connection closed with message: " + reason + " (Code: " + code + ")"; } } /** * WebSocket onerror event. */ socket.onerror = function (event) { label.innerHTML = "Error: " + event; } /** * Disconnect and close the connection. */ // buttonStop.onclick = function (event) { // if (socket.readyState == WebSocket.OPEN) { // socket.close(); // } // } /** * Send the message and empty the text field. */ buttonSend.onclick = function (event) { sendText(); } /** * Send the message and empty the text field. */ // textView.onkeypress = function (event) { // if (event.keyCode == 13) { // sendText(); // } // } /** * Handle the drop event. */ // document.ondrop = function (event) { // var file = event.dataTransfer.files[0]; // socket.send(file); // return false; // } /** * Prevent the default behaviour of the dragover event. */ // document.ondragover = function (event) { // event.preventDefault(); // } /** * Send a text message using WebSocket. */ function sendText() { if (socket.readyState == WebSocket.OPEN) { //var json = '{ "name" : "' + nameView.value + '", "message" : "' + textView.value + '" }'; App.blockUI({ target: $('#div_imageshow'), iconOnly: true }); socket.send("Acuireimage"); // textView.value = ""; } } } ```
@daxfrancis
Copy link
Author

/**
* Executed when the page has finished loading.
*/
window.onload = function () {

    // Create a reference for the required DOM elements.
    //        var nameView = document.getElementById("name-view");
    //        var textView = document.getElementById("text-view");
    var buttonSend = document.getElementById("buttonSend");
    // var buttonStop = document.getElementById("stop-button");
    var label = document.getElementById("status-label");
    // var chatArea = document.getElementById("chat-area");
    var image = document.getElementById("img_Scannedimage");
    var imageshow = document.getElementById("Imageshow");
    // Connect to the WebSocket server!
    var socket = new WebSocket("wss://127.0.0.1:9393");
    //socket.binaryType = "arraybuffer";
    /**
    * WebSocket onopen event.
    */
    socket.onopen = function (event) {
        label.innerHTML = "Connection open";
        $("#div_downaloadJFWebTWAINService").hide();
        $("#div_imageshowhide").show();

    }

    /**
    * WebSocket onmessage event.
    */
    socket.onmessage = function (event) {
        if (typeof event.data === "string") {

            // Create a JSON object.
            var jsonObject = JSON.parse(event.data);

            // Extract the values for each key.
            var userName = jsonObject.name;
            var userMessage = jsonObject.message;
            alert(event.data);
            // Display message.
            // chatArea.innerHTML = chatArea.innerHTML + "<p>" + userName + " says: <strong>" + userMessage + "</strong>" + "</p>";

            // Scroll to bottom.
            // chatArea.scrollTop = chatArea.scrollHeight;
        }
        else if (event.data instanceof Blob) {

            // Get the raw data and create an image element.
            var blob = event.data;

            window.URL = window.URL || window.webkitURL;
            var source = window.URL.createObjectURL(blob);


            image.src = source;
            image.alt = "Image generated from blob";
            imageshow.src = source;
            imageshow.alt = "Scanned Copy";
            App.unblockUI($('#div_imageshow'));
            // document.body.appendChild(image);
        }
        else if (event.data === "ArrayBuffer") {
            alert(event.data);
        }
    }

    /**
    * WebSocket onclose event.
    */
    socket.onclose = function (event) {
        var code = event.code;
        var reason = event.reason;
        var wasClean = event.wasClean;

        if (wasClean) {
            label.innerHTML = "Connection closed normally.";
        }
        else {
            label.innerHTML = "Connection closed with message: " + reason + " (Code: " + code + ")";
        }
    }

    /**
    * WebSocket onerror event.
    */
    socket.onerror = function (event) {
        label.innerHTML = "Error: " + event;

    }

    /**
    * Disconnect and close the connection.
    */
    //        buttonStop.onclick = function (event) {
    //            if (socket.readyState == WebSocket.OPEN) {
    //                socket.close();
    //            }
    //        }

    /**
    * Send the message and empty the text field.
    */
    buttonSend.onclick = function (event) {
        sendText();
    }

    /**
    * Send the message and empty the text field.
    */
    //        textView.onkeypress = function (event) {
    //            if (event.keyCode == 13) {
    //                sendText();
    //            }
    //        }

    /**
    * Handle the drop event.
    */
    //        document.ondrop = function (event) {
    //            var file = event.dataTransfer.files[0];
    //            socket.send(file);

    //            return false;
    //        }

    /**
    * Prevent the default behaviour of the dragover event.
    */
    //        document.ondragover = function (event) {
    //            event.preventDefault();
    //        }

    /**
    * Send a text message using WebSocket.
    */
    function sendText() {
        debugger;
        if (socket.readyState == WebSocket.OPEN) {
            //var json = '{ "name" : "' + nameView.value + '", "message" : "' + textView.value + '" }';
            App.blockUI({ target: $('#div_imageshow'), iconOnly: true });
            socket.send("Acuireimage");

            // textView.value = "";
        }
    }
}

@statianzo
Copy link
Owner

Make sure your self-generated certificate is in the trusted root.

@daxfrancis
Copy link
Author

My scenario is I have a server and a client
server running a https://Website
Client running a windows application of the socket server
user will use the https://Website in Client to communicate with windows application which runs in the Client using socket server
it is worked on http but not in https.So I used the code line

var server = new WebSocketServer("wss://localhost:9393");
server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("servercert.pfx", "jforce");
in window application

and the code
var socket = new WebSocket("wss://127.0.0.1:9393");
in javascript of https://Website to connect it but not working

as you said I have put the self-generated certificate in the trusted root. The self-generated certificate is generated in Server and I have installed in trusted root of both Server and Client but still not working.
Can we use the crt or p7b certificate in fleck?
Please help me.

@statianzo
Copy link
Owner

What browser are you testing with?

@rickparrish
Copy link
Collaborator

Try entering https://Website:9393 in Firefox. This should have it connect to your Fleck server, and if it dislikes the cert it should let you know.

Also, did you reboot after adding the cert to the trusted root? I know editing a cert (ie disabling it) requires a reboot, so adding one may also require one.

@statianzo
Copy link
Owner

A note about firefox, it has it's own set of certificates separate from the windows store. It's under Preferences>Advanced>Certificates menu.

@daxfrancis
Copy link
Author

I am testing in Firefox and Chrome both is not working.

In the address bar of Chrome is showing "The identity of this website has not been verified. Server Certificate does not match the URL" Is this is the problem?.

I have a valid certificate but that one is gd-g2_iis_intermediates.p7b and 2d40ae8147a7ea49.crt verified by Godaddy. How can I use this kind of certificate in Fleck.

@statianzo
Copy link
Owner

The Common Name of the cert doesn't match "localhost". Have you tested with a self-signed certificate?

@daxfrancis
Copy link
Author

I have generated a self-signed certificate in Server machine and imported in Trusted Root Certification Authorities .
I have exported it as localhost.pfx and import this certificate in Client machine's Trusted Root Certification and placed a copy of it in Socket Server windows application running folder

In Socket Server windows application that runs on client machine I have coded as

var server = new WebSocketServer("wss://localhost:9393");
server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("localhost.pfx","password");

I have tested it in Chrome and Firefox.But still I can't connect from my website through
var socket = new WebSocket("wss://127.0.0.1:9393");

How can I find any solution to solve this problem.

@statianzo
Copy link
Owner

What is the Common Name in your cert? I ask because if the Common Name is "localhost" and you're connecting to 127.0.0.1, then it's not a match. If your Common Name is localhost, change your javascript to new WebSocket('wss://localhost:9393')

@daxfrancis
Copy link
Author

Hi,
Thank you for your valuable help. It is working now. I just created a self signed certificate with common name "localhost" from http://www.selfsignedcertificate.com/ and imported it to "Trusted Root Certification Authorities" and it works fine.

but one problem exist that is only working in chorme but not in firefox any idea.I appreciate your help.

@statianzo
Copy link
Owner

Firefox has its own certificate manager in the advanced settings. Add the certificate there.

@amjadaliup
Copy link

hi,
how to add certificate from http://www.selfsignedcertificate.com/ into our code?

@amjadaliup
Copy link

I added code server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(@"C:\Users\amjad\Downloads\34001582_localhost.cert");
But it shows error WebSocket connection to 'wss://localhost:3399' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

@AdrianBathurst
Copy link

Refer to this issue... #214

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants