如何使用nodejs服务器和reactjs处理socket.io身份验证错误?

发布于 2025-01-17 17:16:23 字数 1666 浏览 0 评论 0原文

当身份验证期间连接失败(JWT 令牌错误)时,我们尝试显示错误。

为此,我们在服务器上有一个中间件,用于验证令牌的有效性,并且如果令牌无效,则预计会返回错误:

io.use((socket, next) => 
{
    jwt.verify(socket.handshake?.query?.refreshToken, process.env.REF_JWT_SEC, (err, decoded) =>
    {
        if(decoded?._id && !err) 
        {
            socket.decoded = decoded._id;
            return next();
        }
        else
        {
            let err = new Error('authentication_error')
            err.data = { content : 'refreshToken error!' };
            return next(err);
        }
    });
});

在客户端上,我们有多个 socket.on() 实例:

const refreshToken = localStorage.getItem('refresh_token');
const socket = io(
  "http://localhost:4000",
  {
    query: { refreshToken },
  },
);
...
export const Chat = () => {
  ...
  useEffect(() => {
    socket.on("connect_error", err => {
      console.log(err); // <-- error we're trying to log
    });

    socket.on("error", err => {
      console.log(err); // <-- error we're trying to log
    });

    socket.on("message", ({id, text, sender}) => {
      console.log('# socket io res :', id, text, sender)
    })

    return () => {
      socket.disconnect()
    }
  }, []);
  ...
}

当尝试通过发送不正确的令牌“ThisIsSomeIn CorrectToken”)来触发错误时,如预期的那样,发送/接收消息不起作用。但是,没有记录任何错误

在客户端的控制台中我们可以看到对socket.io的请求:

请注意,当我保存 ReactJS 代码时,错误会以某种方式显示在客户端日志中,但如果我完全刷新浏览器或重新渲染组件,则错误不会显示在

We are trying to display an error when the connection has failed during authentication (wrong JWT token).

For that, we have a middleware on the server that verifies the validity of the token and is expected to return an error if the token is invalid :

io.use((socket, next) => 
{
    jwt.verify(socket.handshake?.query?.refreshToken, process.env.REF_JWT_SEC, (err, decoded) =>
    {
        if(decoded?._id && !err) 
        {
            socket.decoded = decoded._id;
            return next();
        }
        else
        {
            let err = new Error('authentication_error')
            err.data = { content : 'refreshToken error!' };
            return next(err);
        }
    });
});

On the client we have multiple socket.on() instances :

const refreshToken = localStorage.getItem('refresh_token');
const socket = io(
  "http://localhost:4000",
  {
    query: { refreshToken },
  },
);
...
export const Chat = () => {
  ...
  useEffect(() => {
    socket.on("connect_error", err => {
      console.log(err); // <-- error we're trying to log
    });

    socket.on("error", err => {
      console.log(err); // <-- error we're trying to log
    });

    socket.on("message", ({id, text, sender}) => {
      console.log('# socket io res :', id, text, sender)
    })

    return () => {
      socket.disconnect()
    }
  }, []);
  ...
}

While trying to trigger the error by sending an incorrect token ("ThisIsSomeIncorrectToken"), as expected, sending/recieving messages doesn't work. However, no error is being logged.

In the client's console we can see the requests to socket.io:
Network requests to the server

Note that somehow the error shows up in the client logs when I save my reactjs code, but not if I refresh completely the browser or re-render the component.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文