【问题标题】:How to authenticate in websockets, using node and express-ws如何使用 node 和 express-ws 在 websockets 中进行身份验证
【发布时间】:2020-03-21 20:52:01
【问题描述】:

我正在使用节点 10.16.0,表示 4.0.0 和 express-ws 模块。在我使用 REST 的正常路由中,我使用中间件来检查是否存在带有令牌的标头并验证该令牌。

我如何为 websocket 做同样的事情?

我不能只向 ws 添加一个标头并将其传递给节点路由,即使 express-ws 允许轻松创建 express 样式的路由。

目前,我正在使用http服务器创建一个ws服务器,然后分离不同的快速路由

//app.js
const app = express();

const wsHttpServer = http.createServer();
wsHttpServer.listen(5001);
const expressWs = require('express-ws')(app , wsHttpServer);

app.use(cors());

app.use(express.static(path.join(__dirname,'public'))); 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.json());
app.use(express.urlencoded({extended:false})); 

app.use('/ws', require('./routes/wsroute')); 
app.use('/login', require('./routes/login'));


const port = process.env.PORT || 4000;
app.listen(port, ()=>{
    console.log('server runs on port ', port);
});

exports.expressWs = expressWs;

然后对于 ws 路由,根据 express-ws 示例

//wsroute.js
router.ws('/users/:name/:date/:time', /*token.validate(),*/  (ws, req) => { 
    const name = req.params.name;  
    const date = req.params.date;
    const time = req.params.time;  
    console.log('ws route');
    console.log('ws route',name, date, time);    
});

如果我取消注释 token.validate() 部分,这将永远不会控制日志,因为没有带有令牌的标头。

如何像在 REST 中一样向 ws 添加标头,以便可以自动检查它?我猜如果ws服务器是使用http服务器初始化的,并且ws路由还包含req,我能做到吗?

或者还有其他方法吗?

谢谢

【问题讨论】:

    标签: node.js express authentication websocket access-token


    【解决方案1】:

    Websockets token authentication using middleware and express in node.js 重复。按照那里的例子。

    监听 wsHttpServer.on('upgrade') 事件并在那里执行您选择的身份验证。如果您愿意,您还可以在升级事件到达您的路线之前附加一个标头。

    【讨论】:

      猜你喜欢
      • 2016-08-15
      • 2014-12-01
      • 2020-01-20
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2012-01-13
      • 2017-02-18
      相关资源
      最近更新 更多