Websockets token authentication using middleware and express in node.js

后端 未结 2 1601
臣服心动
臣服心动 2021-01-24 02:12

I use node.js, express and express-ws that is based on ws

Express-ws allows to create express-like endpoints for websockets.

I am looking for a solution to auth

相关标签:
2条回答
  • 2021-01-24 02:40

    On your client side, you should pass an array of strings instead of object, but you must set a header for your HTTP response with a key and value:

    key : headeSec-WebSocket-Protocol
    value : corresponding protocol used in front.
    
    0 讨论(0)
  • 2021-01-24 02:46

    1) In my experience there is no available express.js middleware and the solution i found requires to listen to the upgrade event on your http server and blocking access to your socket connection before it reaches ws routes.

    2) Your browser will not allow setting additional headers during websocket connection on the client side. It will send though the cookies so you can make use of express-session to authorize on your server first the user, a cookie will be set on the browser and that cookie will be sent over during the websocket connection.

    3) You can do like in this answer Intercept (and potentially deny) web socket upgrade request Copying the code here from there for your own perusal.

    **wsHttpServer**.on('upgrade', function (req, socket, head) {
          var validationResult = validateCookie(req.headers.cookie);
          if (validationResult) {
            //...
          } else {
            socket.write('HTTP/1.1 401 Web Socket Protocol Handshake\r\n' +
                         'Upgrade: WebSocket\r\n' +
                         'Connection: Upgrade\r\n' +
                         '\r\n');
                         socket.close();
                         socket.destroy();
                         return;
          }
          //...
        });
    
    0 讨论(0)
提交回复
热议问题