如何使用nodejs服务器和reactjs处理socket.io身份验证错误?
当身份验证期间连接失败(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”
)来触发错误时,如预期的那样,发送/接收消息不起作用。但是,没有记录任何错误。
请注意,当我保存 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:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论