如何验证socket.io连接?我的应用程序使用来自另一台服务器(python)的登录端点来获取令牌,每当用户在节点侧打开套接字连接时如何使用该令牌?
io.on('connection', function(socket) { socket.on('message', function(message) { io.emit('message', message); }); });
和客户端:
var token = sessionStorage.token; var socket = io.connect('http://localhost:3000', { query: 'token=' + token });
如果令牌是在python中创建的:
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
如何使用此令牌对节点中的套接字连接进行身份验证?
令牌是否在另一台服务器上创建都没有关系。如果您拥有正确的密钥和算法,您仍然可以验证它。
jsonwebtoken
客户
const {token} = sessionStorage; const socket = io.connect('http://localhost:3000', { query: {token} });
服务器
const io = require('socket.io')(); 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); }); });
socketio-jwt
此模块使客户端和服务器端的身份验证更加容易。只是看看他们的例子。
const {token} = sessionStorage; const socket = io.connect('http://localhost:3000'); socket.on('connect', function (socket) { socket .on('authenticated', function () { //do other things }) .emit('authenticate', {token}); //send the jwt });
const io = require('socket.io')(); const socketioJwt = require('socketio-jwt'); io.sockets .on('connection', socketioJwt.authorize({ secret: 'SECRET_KEY', timeout: 15000 // 15 seconds to send the authentication message })).on('authenticated', function(socket) { //this socket is authenticated, we are good to handle more events from it. console.log(`Hello! ${socket.decoded_token.name}`); });