【问题标题】:Authenticate jwt in socket.io在 socket.io 中验证 jwt
【发布时间】:2021-12-25 05:19:11
【问题描述】:

这是我的登录代码:

router.post("/", async (req, res) => {
const { email, password } = req.body;
console.log(email, password);

try {
  if (email && password) {
  const accessToken = jwt.sign(email, process.env.TOKEN_SECRET)

      res.json(accessToken);
 } else res.sendStatus(400);
} catch (error) {
  res.sendStatus(500);
}
});

我想在我的其他文件中使用 accessToken:

io.on('connection', socket => {
socket.on('joinRoom', ({ username, room }) => {
 const user = userJoin(socket.id, username, room, *accessToken*);

socket.join(user.room);
})

谁能告诉我该怎么做?谢谢!

【问题讨论】:

    标签: node.js socket.io jwt


    【解决方案1】:

    您需要使用middleware 函数:

    //client side send token
    const socket = io({
      auth: {
        token: "abc"
      }
    });
    
    //server side
    io.use((socket, next) => {
      const token = socket.handshake.auth.token;
      // ...
    });
    

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 2018-08-03
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 2018-12-21
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多