JWT with socket.io



当我尝试与JWT建立连接时,它没有给我任何东西,我不确定我做错了什么,因为我不太熟悉JWT

我无法在localhost:4000上做任何事情,因为没有连接

你们有什么建议吗?谢谢你的帮助:)

app.js

var io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
const jwt = require("jsonwebtoken");
io.use(function(socket, next){
if (socket.handshake.query && socket.handshake.query.token){
jwt.verify(socket.handshake.query.token, 'SECRET_KEY', function(err, decoded) {
if (err) return next(new Error('Authentication error'));
socket.decoded = decoded;
next();
});
}
else {
next(new Error('Authentication error'));
}    
})
.on('connection', function(socket) {
// Connection now authenticated to receive further events
socket.on('message', function(message) {
io.emit('message', message);
});
})

chat.js


const socket = io()

const {token} = sessionStorage;
socket.on('connect', function (socket) {
socket
.on('authenticated', function () {
//do other things
})
.emit('authenticate', {token}); //send the jwt


});

令牌必须在auth有效载荷中发送:

const { token } = sessionStorage;
const socket = io({
auth: {
token
}
});

这个值可以在服务器端找到:

io.use((socket, next) => {
const token = socket.handshake.auth.token;
jwt.verify(token, 'SECRET_KEY', (err, decoded) => {
if (err) return next(new Error('Authentication error'));
socket.decoded = decoded;
next();
});
});

参考:https://socket.io/docs/v4/client-options/auth

最新更新