Ws: How to Reject a Connection Request?

Created on 24 Jun 2015  路  8Comments  路  Source: websockets/ws

Most helpful comment

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.

All 8 comments

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.

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?

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.

@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

You can use verifyClient as suggested by @liviubunda.

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

@r03ert0

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

  return false;
};

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');
Was this page helpful?
0 / 5 - 0 ratings

Related issues

pacmac picture pacmac  路  3Comments

bartosz-m picture bartosz-m  路  3Comments

sherikapotein picture sherikapotein  路  3Comments

ImBundle picture ImBundle  路  3Comments

NodePing picture NodePing  路  5Comments