拦截(并可能拒绝)Web套接字升级请求 [英] Intercept (and potentially deny) web socket upgrade request

查看:59
本文介绍了拦截(并可能拒绝)Web套接字升级请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要向其发送Web套接字升级请求的Node.js服务器.该请求的Authorization标头包含登录信息,我需要将其与数据库条目进行比较.我不确定如何停止打开Web套接字连接,直到执行数据库查询回调之后.

I have a Node.js server that I am sending a web socket upgrade request to. The Authorization header of this request contains login information, which I need to compare against a database entry. I'm unsure how I can stop the web socket connection from opening until after my database query callback is executed.

以下是我目前正在做的事情的简化:

The following is a simplification of what I am currently doing:

var Express = require('express')
var app = Express() 
server = app.listen(app.get("port"), function () {})
server.on("upgrade", function (request, socket) {
//Query database
//On success set "authenticated" flag on request (later accessed through socket.upgradeReq)
//On failure abort connection
})

这有效,但是在短时间内套接字已打开,但我尚未验证Authorization标头,因此恶意用户有可能发送/接收数据.我正在通过使用已认证"标志来减轻实施过程中的这种风险,但是似乎必须有一种更好的方法.

This works, but there is a brief period of time where the socket is open but I haven't verified the Authorization header, so it would be possible for a malicious user to send/receive data. I'm mitigating this risk in my implementation through the use of an "authenticated" flag, but it seems like there must be a better way.

我尝试了以下操作,但是它们似乎拦截了除升级请求之外的所有请求:

I tried the following things, but while they seemed to intercept all requests except the upgrade ones:

Attempt #1: 
app.use(function (request, response, next) {
//Query database, only call next if authenticated
next()
})

Attempt #2:
app.all("*", function (request, response, next) {
//Query database, only call next if authenticated
    next()
})

可能值得注意的是: 我也有一个HTTP服务器,它使用相同的端口并接受POST请求进行注册和登录.

Possibly worth noting: I do have an HTTP server as well, it uses the same port and accepts POST requests for registration and login.

谢谢您的帮助,如果需要其他信息,请告诉我.

Thank you for any assistance, please let me know if additional information is needed.

推荐答案

我不确定这是否是正确的HTTP协议通信,但对于我来说似乎可行:

I'm not sure if this is correct HTTP protocol communication but it seems to be working in my case:

server.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;
  }
  //...
});

这篇关于拦截(并可能拒绝)Web套接字升级请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆