How do we prevent websocket CSRF attacks?
That is, someone can essentially find the websocket url, then, from the browser console, define a new websocket connection to that url and ultimately communicate with the database. I found a good explanation of how it's done here: https://medium.com/@osamaavvan/exploiting-websocket-application-wide-xss-csrf-66e9e2ac8dfa
I'm using the ws library with node.js and have looked through their documentation. They have provided an example but right at the most important part, they have essentially said "write it yourself": https://github.com/websockets/ws#client-authentication
I have found this answer but, as I've commented, the "validateCookie" produces an error as it is not defined: https://stackoverflow.com/a/52792563/11930305
I've looked at an example referenced in the ws documentation, which looks like this:
if (!request.session.userId) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
where:
const uuid = require('uuid');
const id = uuid.v4();
req.session.userId = id;
I haven't tried this as it'd be nice to have a solution that doesn't require yet another library but perhaps this is the best way.
What's the best and most simple way to prevent websocket CSRF attacks?