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

How to Reject a Connection Request? #517

Closed
ma11hew28 opened this issue Jun 24, 2015 · 8 comments
Closed

How to Reject a Connection Request? #517

ma11hew28 opened this issue Jun 24, 2015 · 8 comments

Comments

@ma11hew28
Copy link

http://stackoverflow.com/questions/31030115/node-js-ws-reject-connection-request

@woverton
Copy link

This is not straight up built in, but you could add it into your program (Note, this will not block the connection from ever happening, more it will allow you to implement a handshake of your own).

this.wss = new WebSocketServer({
    port: process.env.PORT
});

this.wss.on('connection', function(socket){
    if(!iWantThisSocketToConnect(socket)){
        socket.close();
        return;
    }
});

For example you could check the ip of the socket. http://stackoverflow.com/questions/14822708/how-to-get-client-ip-address-using-websocket-einaros-ws-lib-in-node-js

Also, your link is broken.

@ma11hew28
Copy link
Author

Sorry for the broken link. It looks like the Stack Overflow moderators deleted my question. I'm not sure why.

Thank you for suggesting I close a connection immediately after it's been accepted.

The websocket Node.js module allows you to reject a WebSocket Connection Request before it's accepted. Is this possible with the ws Node.js module? If so, how?

@woverton
Copy link

I am not a ws dev, so there may be a super special undocumented way that is not obvious by looking at the code. However...

I figured it out! Now gaze upon my ugly test code!

var server = function() {

    var WebSocketServer = require('ws').Server;
    var http = require("http");

    var server = http.createServer(function(req, res) {
        res.end("Hello");
    });

    server.on("upgrade", function(req, socket, head) {

        if(iDontWantThemToBecomeAWebSocket()){
            socket.destroy(); //<-------------------------- Close Connection
        }
    })

    var wss = new WebSocketServer({
        server: server
    });

    server.listen(8000);

    wss.on('connection', function connection(ws) {
        ws.on('message', function incoming(message) {
            console.log('received: %s', message);
        });

        ws.send('something');
    });

}

var client = function() {

    var WebSocket = require('ws');

    var ws = new WebSocket('ws://localhost:8000');

    ws.on('open', function open() {
        ws.send('something');
    });

    ws.on('message', function(data, flags) {
        console.log(data)
    });

}

server();
setTimeout(client, 500);

You need to create your own http server and then listen for when it gets upgraded.

@tenxliviu
Copy link

@mattdipasquale

There is such a thing, as @woverton mentioned:

a super special undocumented way

The WebSocketServer server constructor accepts a parameter called verifyClient. You can figure out more on how to use this from the WebSocketServer unit tests found here: https://github.com/websockets/ws/blob/master/test/WebSocketServer.test.js

Also, if you want to detect in the client that the connection was closed due to authentication/authorization issues, you can use the 'unexpected-response' event. This event is specific to the ws module, other clients may handle this differently or not handle it at all. You can find more details on how to use this in the WebSocket unit tests found here:
https://github.com/websockets/ws/blob/master/test/WebSocket.test.js

@lpinca
Copy link
Member

lpinca commented Nov 9, 2016

You can use verifyClient as suggested by @liviubunda.

@lpinca lpinca closed this as completed Nov 9, 2016
@r03ert0
Copy link

r03ert0 commented Nov 21, 2016

how would you detect the client's IP, for example, at verifyClient? For example, if you wanted to blacklist them?

@lpinca
Copy link
Member

lpinca commented Nov 22, 2016

@r03ert0

options.verifyClient = (info) => {
  if (info.req.connection.remoteAddress === IP ) return true;

  return false;
};

@nolimitdev
Copy link

nolimitdev commented Jun 7, 2017

Why following code causes that after first connection with invalid JSON data any other connections are closed (error from chrome: "WebSocket connection to ... failed: Connection closed before receiving a handshake response") although JSON data are valid? Is it correct to use "return" keyword in onconnection callback?

wss.on('connection', function(ws, req){
    // validate input
    try {
        var data = JSON.parse(decodeURIComponent(req.url.substring(1)));
    }
    catch(e) {
        console.log('connection closed due to invalid JSON input data');
        ws.close();
        return;
    };
    // input is ok, do something...
    console.log('Hello');
}

In browser I use somethink like this:

// to test connection with valid input JSON data
new WebSocket('ws://server:port/' + encodeURIComponent(JSON.stringify({ key: 'value' })));

// to test connection with INVALID input JSON data
new WebSocket('ws://server:port/invalidjson');

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

6 participants