首页 > 解决方案 > 在 socket.io 中验证 jwt

问题描述

这是我的登录代码:

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.jssocket.iojwt

解决方案


您需要使用中间件功能:

//client side send token
const socket = io({
  auth: {
    token: "abc"
  }
});

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

推荐阅读