How does Connect's session middleware's signed cookies work?

佐手、 提交于 2019-12-14 03:47:50

问题


I would like an explanation on how the connect.sid cookies work in the Connect Node.js framework. I noticed that they are formated like,

s:hash.signature

I don't understand how the signature is used when the hash is more than capable of being used to access the session data from a memory store or redis store.

Also, I don't understand why the s: is even in the cookie; what is it's purpose.

I'm hearing that the signature is used to "sign" the hash. What exactly is meant by "sign" or "signed"? I need an explanation on this process as well.

Thanks!


回答1:


The signature is there so the server can verify that it generated the cookie, not some random attacker.

Only the person who knows the secret used to sign can sign it with the same value.

"s:" is there so it is easy to know it is a signed cookie, as opposed to some other format (like unsigned).

Here's a way to retrieve data from a signed cookie and fail is signature is incorrect. Only partial code extracted from actual app, but you should get the idea.

var cookie = require('cookie');
var connect = require('connect');
var secret = "same secret used to sign cookies";

socketio.set('authorization', function(data, cb) {
  if (data.headers.cookie) {
    var sessionCookie = cookie.parse(data.headers.cookie);
    var sessionID = connect.utils.parseSignedCookie(sessionCookie['connect.sid'], secret);
    // do something here with decoded value
  }
});

You need to use the "authorization" function from socket.io so you have access to the headers. That code works when using xhr-polling transport, I'm not sure this would work for websocket for example.



来源:https://stackoverflow.com/questions/14843960/how-does-connects-session-middlewares-signed-cookies-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!