JWTを使用したソケットIO接続の認証 質問する

JWTを使用したソケットIO接続の認証 質問する

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')

このトークンを使用してノード内のソケット接続を認証するにはどうすればよいですか?

ベストアンサー1

トークンが別のサーバーで作成されたかどうかは関係ありません。正しい秘密鍵とアルゴリズムがあれば、トークンを検証できます。

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

おすすめ記事