Dave Dave - 3 months ago 8
Node.js Question

Allow websocket connection only from one URL

My websocket application accepting connections like this:

wsServer.on('request', function(request) {
console.log(request);
if(request.origin == "https://www.my-domain.com"){

var connection = request.accept(null, request.origin);

/* some lines of code
...
*/

} else {
//here I want block request
}


Is here some function like
.decline()
? or
.notAccept()
or...?
When I trying connect to my websocket from different URL, my status is "pending" for a long time.
enter image description here

Answer

It's shown here:

wsServer.on('request', function(request) {
  if (! originIsAllowed(request.origin)) {
    // Make sure we only accept requests from an allowed origin 
    request.reject();
    console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
    return;
  }
  ...
});

You'd have to replace originIsAllowed(request.origin) with your own check.

Comments