code

socket.io 및 세션?

codestyles 2020. 8. 27. 07:47
반응형

socket.io 및 세션?


Express 프레임 워크를 사용하고 있습니다. socket.io에서 세션 데이터에 도달하고 싶습니다. client.listener.server.dynamicViewHelpers 데이터로 express dynamicHelpers를 시도했지만 세션 데이터를 가져올 수 없습니다. 이 작업을 수행하는 간단한 방법이 있습니까? 코드를 참조하십시오

app.listen(3000);

var io = require('socket.io');
var io = io.listen(app);

io.on('connection', function(client){
    // I want to use session data here
    client.on('message', function(message){
        // or here
    });
    client.on('disconnect', function(){
        // or here
    }); 
});

이것은 flashsocket 전송을 통과하는 소켓에 대해서는 작동하지 않지만 (서버에 필요한 쿠키를 보내지 않음) 다른 모든 것에 대해서는 안정적으로 작동합니다. 내 코드에서 flashsocket 전송을 비활성화했습니다.

작동하도록하려면 익스프레스 / 연결 측에서 명시 적으로 세션 저장소를 정의하여 소켓 내에서 사용할 수 있습니다.

MemoryStore = require('connect/middleware/session/memory'),
var session_store = new MemoryStore();
app.configure(function () {
  app.use(express.session({ store: session_store }));
});

그런 다음 소켓 코드 내에 connect 프레임 워크를 포함하여 쿠키 구문 분석을 사용하여 쿠키에서 connect.sid를 검색 할 수 있습니다. 그런 다음 다음과 같이 connect.sid가있는 세션 저장소에서 세션을 찾습니다.

var connect = require('connect');
io.on('connection', function(socket_client) {
  var cookie_string = socket_client.request.headers.cookie;
  var parsed_cookies = connect.utils.parseCookie(cookie_string);
  var connect_sid = parsed_cookies['connect.sid'];
  if (connect_sid) {
    session_store.get(connect_sid, function (error, session) {
      //HOORAY NOW YOU'VE GOT THE SESSION OBJECT!!!!
    });
  }
});

그런 다음 필요에 따라 세션을 사용할 수 있습니다.


Socket.IO-sessions 모듈 솔루션은 클라이언트 (스크립팅) 수준에서 세션 ID를 노출하여 앱을 XSS 공격에 노출합니다.

대신 솔루션을 확인하십시오 (Socket.IO> = v0.7의 경우). 여기에서 문서를 참조 하십시오 .


나는 바퀴를 완전히 재발 명하지 말 것을 제안합니다. 필요한 도구는 이미 npm 패키지입니다. 이것이 필요한 것이라고 생각합니다 : session.socket.io 요즘 사용하고 있으며 매우 도움이 될 것 같습니다 !! express-session을 socket.io 레이어에 연결하면 많은 이점이 있습니다!


Edit: After trying some modules that didn't work, I've actually gone and written my own library to do this. Shameless plug: go check it out at https://github.com/aviddiviner/Socket.IO-sessions. I'll leave my old post below for historical purposes:


I got this work quite neatly without having to bypass the flashsocket transport as per pr0zac's solution above. I am also using express with Socket.IO. Here's how.

First, pass the session ID to the view:

app.get('/', function(req,res){
  res.render('index.ejs', {
    locals: { 
      connect_sid: req.sessionID
      // ...
    }
  });
});

Then in your view, link it in with Socket.IO client-side:

<script>
  var sid = '<%= connect_sid %>';
  var socket = new io.Socket();
  socket.connect();
</script>
<input type="button" value="Ping" onclick="socket.send({sid:sid, msg:'ping'});"/>

Then in your server-side Socket.IO listener, pick it up and read/write the session data:

var socket = io.listen(app);
socket.on('connection', function(client){
  client.on('message', function(message){
    session_store.get(message.sid, function(error, session){
      session.pings = session.pings + 1 || 1;
      client.send("You have made " + session.pings + " pings.");
      session_store.set(message.sid, session);  // Save the session
    });
  });
});

In my case, my session_store is Redis, using the redis-connect library.

var RedisStore = require('connect-redis');
var session_store = new RedisStore;
// ...
app.use(express.session({ store: session_store }));

Hope this helps someone who finds this post while searching Google (as I did ;)


See this: Socket.IO Authentication

I would suggest not fetching anything via client.request... or client.listener... as that is not directly attached to the client object and always point to the last logged in user!


Check out Socket.IO-connect

Connect WebSocket Middleware Wrapper Around Socket.IO-node https://github.com/bnoguchi/Socket.IO-connect

This will allow you to push the Socket.IO request(s) down the Express/Connect middleware stack before handling it with Socket.IO event handlers, giving you access to the session, cookies, and more. Although, I'm not sure that it works with all of Socket.IO's transports.


You can make use of express-socket.io-session .

Share a cookie-based express-session middleware with socket.io. Works with express > 4.0.0 and socket.io > 1.0.0 and won't be backward compatible.

Worked for me!!


You can have a look at this: https://github.com/bmeck/session-web-sockets

or alternatively you can use:

io.on('connection', function(client) { 
  var session = client.listener.server.viewHelpers; 
  // use session here 
});

Hope this helps.


I am not sure that I am doing it right. https://github.com/LearnBoost/socket.io/wiki/Authorizing

With the handshake data, you can access to the cookies. And in the cookies, you can grab connect.sid which is the session id for each client. And then use the connect.sid to get the session data from database (I am assuming you are using RedisStore)

참고URL : https://stackoverflow.com/questions/4641053/socket-io-and-session

반응형