programing

JWT를 사용한 소켓 IO 연결 인증

goodsources 2023. 9. 3. 16:16
반응형

JWT를 사용한 소켓 IO 연결 인증

socket.io 연결을 인증하려면 어떻게 해야 합니까?내 응용 프로그램은 토큰을 얻기 위해 다른 서버(파이썬)의 로그인 끝점을 사용하는데, 사용자가 노드 측에서 소켓 연결을 열 때마다 어떻게 해당 토큰을 사용할 수 있습니까?

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

노드에서 소켓 연결을 인증하는 데 이 토큰을 사용하려면 어떻게 해야 합니까?

토큰이 다른 서버에 작성되었는지 여부는 중요하지 않습니다.올바른 비밀 키와 알고리즘이 있으면 확인할 수 있습니다.

모듈을 사용한 구현

고객

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

모듈을 사용한 구현

이 모듈을 사용하면 클라이언트와 서버 모두에서 인증을 훨씬 쉽게 수행할 수 있습니다.그들의 예를 확인해 보세요.

고객

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

인정된 답변에 코멘트를 추가할 만큼 평판이 좋지 않기 때문에:

const socketioJwt = required "subio-subt";

실제로 auth0의 repo의 일부가 아니며 타사 커뮤니티 기반 패키지입니다.

auth0 repo 링크가 404페이지이므로 위 답변을 업데이트해야 합니다.

소켓에서 사용자를 인증하고 사용자의 데이터를 저장하는 방법에 대한 자세한 기사를 작성했습니다.

https://medium.com/ @httpsemrafay/사용자 인증 및 저장 방법-19b262496 febec.

클라이언트 사이드 코드

import io from "socket.io-client";

const SERVER = "localhost:4000";
const socket = io(SERVER, {
    auth: {
      token: "2c87b3d5412551ad69aet757f81f6a73eb919e5b02467aed419f5b2a9cce2b5aZOzgaM+bpKfjdM9jvez37RTEemAp07kOvEFJ3pBzvj8="
    }
  });

 socket.once('connect', (socketConnection) => {
    console.log('socket connected', socketConnection);
  })
 
// Emit the message and receive data from server in callback
 socket.emit("user send message", {message: "Hi you there" }, callback => {
    if (callback) {
      console.log("--- response from server", callback);
     }
  });

서버 측 코드

const initializeSockets = (io) => {
  io.on('connection', (socket) => {

  decryptAndStoreUserData(socket,io);
  
}

const decryptAndStoreUserData = async (socket,io) => {

    const { token } = socket.handshake.auth; // receive the token from client

    // here i decypt the auth token and get the user data
    const genToken = new Middlewares().token();
    const userData = genToken.decryptTokenForSockets(token);

    // save the data of user in socket
    socket.data.user = userData;

  }

미들웨어 작성:

const jwt = require("jsonwebtoken");

const authSocketMiddleware = (socket, next) => {
  // since you are sending the token with the query
  const token = socket.handshake.query?.token;
  try {
    const decoded = jwt.verify(token, process.env.TOKEN_SECRET_KEY);
    socket.user = decoded;
  } catch (err) {
    return next(new Error("NOT AUTHORIZED"));
  }
  next();
};

module.exports = authSocketMiddleware;

소켓 서버 내부에서 사용

socketServer = (server) => {
  const io = require("socket.io")(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
  });
  // before connection use the middleware
  io.use((socket, next) => {
    authSocketMiddleware(socket, next);
  });
  io.on("connection", (socket) => {
    console.log("user connected", socket.id);
  });
};

언급URL : https://stackoverflow.com/questions/36788831/authenticating-socket-io-connections-using-jwt

반응형