1

I have this code here -

const wss = new SocketServer({ express() });

wss.on('connection', ws => {
    console.log('Client connected');
    ws.on('message', msg => {
        console.log('received: %s', msg);
    });
    ws.on('close', () => console.log('Client disconnected'));
});

Now there are some problems, A D-Dos attack can crash my server.

Is there a way to check a token or something before allowing a stranger to connect to the websocket? Also the socket will be on another domain so cookies won't work.

Or is there a way to disconnect a user if he has not sent the authentication token after connecting.

If it were running and allowing everyone to connect indefinitely, then that's a security risk. Server can be brought down easily.

Thomas
  • 478
  • 4
  • 14

1 Answers1

1

With Socket.io possible a setup like you need, see Authenticating socket io connections

Otherwise you must implement it by your own, but you should follow some standards. The first ugly-hand-made solution that i can think is something like:

wss.on('connection', ws => {
    console.log('Client connected');

    isAuthenticated = false

    ws.on('message', msg => {
        if (!isAuthenticated ) {
            // check if message is a token
            // else comunicates back the error
        }

        console.log('received: %s', msg);
    });

    ws.on('close', () => console.log('Client disconnected'));
});

For the DDos attack, if they have a token they can spam infinite requests: same thing, you should count the incoming massage rate by your own and implementing something like a Throttling policy.

Andrea Franchini
  • 548
  • 4
  • 14