我有一个使用 Redis 作为 session 存储的 Rails 3.2 应用程序。现在我准备在 Node.js 中编写一部分新功能,我希望能够在两个应用程序之间共享 session 信息。
我可以手动读取 _session_id
cookie,然后从名为 rack:session:session_id
的 Redis 键中读取,但这看起来有点像 hack -ish 解决方案。
有没有更好的方法在 Node.js 和 Rails 之间共享 session ?
最佳答案
我已经这样做了,但它确实需要自己制作东西的 fork
首先你需要让 session key 同名。这是最简单的工作。
接下来,我创建了 redis-store gem 的一个分支,并修改了编码的位置。我需要在双方讨论 json,因为为 javascript 找到一个 ruby 风格的 marshal 模块并不容易。 The file where I alter marshalling
我还需要替换连接的 session 中间件部分。创建的散列非常具体,与 rails 创建的散列不匹配。我需要将此留给您解决,因为可能有更好的方法。我本可以 fork connect 但我提取了 connect > middleware > session out 的副本并需要我自己的 in。
您会注意到原始版本如何添加 rails 版本中不存在的基本变量。另外,您需要处理 Rails 创建 session 而不是 Node 的情况,这就是 generateCookie 函数所做的事情。
/***** ORIGINAL *****/
// session hashing function
store.hash = function(req, base) {
return crypto
.createHmac('sha256', secret)
.update(base + fingerprint(req))
.digest('base64')
.replace(/=*$/, '');
};
// generates the new session
store.generate = function(req){
var base = utils.uid(24);
var sessionID = base + '.' + store.hash(req, base);
req.sessionID = sessionID;
req.session = new Session(req);
req.session.cookie = new Cookie(cookie);
};
/***** MODIFIED *****/
// session hashing function
store.hash = function(req, base) {
return crypto
.createHmac('sha1', secret)
.update(base)
.digest('base64')
.replace(/=*$/, '');
};
// generates the new session
store.generate = function(req){
var base = utils.uid(24);
var sessionID = store.hash(req, base);
req.sessionID = sessionID;
req.session = new Session(req);
req.session.cookie = new Cookie(cookie);
};
// generate a new cookie for a pre-existing session from rails without session.cookie
// it must not be a Cookie object (it breaks the merging of cookies)
store.generateCookie = function(sess){
newBlankCookie = new Cookie(cookie);
sess.cookie = newBlankCookie.toJSON();
};
//... at the end of the session.js file
// populate req.session
} else {
if ('undefined' == typeof sess.cookie) store.generateCookie(sess);
store.createSession(req, sess);
next();
}
我希望这对你有用。我花了很多时间才让他们说的一样。
我还发现了一个问题,即 flash 消息存储在 json 中。希望你没有找到那个。 Flash 消息有一个特殊的对象结构,在序列化时 json 会消失。当 flash 消息从 session 中恢复时,您可能没有合适的 flash 对象。我也需要为此打补丁。
关于ruby-on-rails - 有没有一种简单的方法可以在 Rails 和 Node.js 应用程序之间共享存储在 Redis 中的 session 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10300396/