使用 JWT 验证套接字 io 连接 [英] Authenticating socket io connections using JWT

查看:28
本文介绍了使用 JWT 验证套接字 io 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证 socket.io 连接?我的应用程序使用来自另一台服务器 (python) 的登录端点来获取令牌,每当用户在节点端打开套接字连接时,我如何才能使用该令牌?

How can I authenticate a socket.io connection? My application uses a login endpoint from another server (python) to get a token, how can I get use that token whenever a user opens a socket connection on the node side?

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中创建的:

If the token is created in python:

token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')

如何使用此令牌来验证节点中的套接字连接?

How can I use this token to authenticate a socket connection in node?

推荐答案

令牌是否是在另一台服务器上创建的并不重要.如果你有正确的密钥和算法,你仍然可以验证它.

It doesn't matter if the token was created on another server. You can still verify it if you have the right secret key and algorithm.

客户

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模块实现

此模块使客户端和服务器端的身份验证更加容易.只需查看他们的示例即可.

Implementation with socketio-jwt module

This module makes the authentication much easier in both client and server side. Just check out their examples.

客户

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}`);
  });

这篇关于使用 JWT 验证套接字 io 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆