Connect的会话中间件的签名Cookie如何工作?

问题描述:

我想解释一下Connect.sid cookie在Connect Node.js框架中如何工作.我注意到它们的格式是

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

我不明白当散列超出了从内存存储或Redis存储访问会话数据的能力时,如何使用签名.

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.

此外,我不理解为什么s:甚至在cookie中;目的是什么.

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.

谢谢!

签名在那里,因此服务器可以验证它生成了cookie,而不是某些随机攻击者.

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:"在那里,所以很容易知道它是一个签名的cookie,而不是其他格式(如unsigned).

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

这是从已签名的Cookie检索数据的一种方法,并且失败是签名不正确.仅从实际应用程序中提取了部分代码,但您应该了解一下.

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

您需要使用socket.io的授权"功能,以便可以访问标头.该代码在使用xhr-polling传输时有效,例如,我不确定这是否适用于websocket.

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.