我使用Socket.io连接BE和FE,在每次连接中,BE都会验证FE发送的令牌,如果身份验证失败,连接将被切断。
我想知道,当由于身份验证失败而断开连接时,软件开发行业标准应该从be向FE返回什么?
jwt.verify(token, process.env.JWT_SECRET, function (err, decoded) {
if (err) {
// Authentication failed, what should I do here?
socket.disconnect();
} else {
// Authentication passed, do something.
});
}
});
谢谢!
如果您的身份验证在中间件内部,则可以使用next(new Error("message")
。Socket.io会自动将这些错误作为特殊的错误包发送到客户端,这意味着您可以在客户端侦听事件,如下所示:
// Client-side
socket.on("error", data => {
// Do things with the error, such as
// displaying it on the screen or something
});
如果你这样做,那么你的授权必须看起来像这样:
// Server-side
// Here I'm assuming you're using
// socket.io v1.x.x+
io.use((socket, next) => {
jwt.verify(token, process.env.JWT_SECRET, function (err, decoded) {
if (err) {
// Authentication failed, send error packet to client
next(new Error("Auth failed!"));
} else {
// Authentication passed, call next to keep going
next();
}
});
});
如果你需要更多的澄清,这里还有另一个链接:https://socket.io/docs/namespaces/#Handling-中间件错误
您可以向客户端发送消息,告知拒绝连接的原因是身份验证失败