如何使用Redis在NodeJs和PHP之间共享会话?

时间:2023-05-06
本文介绍了如何使用Redis在NodeJs和PHP之间共享会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想使用 RedisNodeJs 应用程序和 PHP 应用程序之间共享服务器会话.我从这个 gist 中获取了大部分代码.

NodeJs 代码:

app.use(session({商店:新的RedisStore({前缀:'session:php:'}),name: 'PHPSESSID',秘密:'node.js'}));app.use(function(req, res, next) {req.session.nodejs = 'node.js!';res.send(JSON.stringify(req.session, null, ' ') );});

它输出:

<代码>{曲奇饼": {原始最大年龄":空,过期":空,httpOnly":真,小路": "/"},护照": {},nodejs":node.js!"}

PHP 代码(我使用 redis-session-php 和 Predis) :

require('redis-session-php/redis-session.php');RedisSession::start();$_SESSION['php'] = 'php';如果 (!isset($_SESSION["cookie"])) {$_SESSION["cookie"] = array();}var_dump($_SESSION);

它输出:

array(2) {[php"] =>字符串(3)php"[cookie"] =>数组(0){}}

问题:我希望两个会话看起来一样,但它们不一样(应用程序在同一个域上运行).使用 PredisClient 中的 set() 设置值有效(但值不会在会话变量上).我发现 这段代码我认为可以用, 使用 set()get() ,但我觉得它会使代码过于复杂.

你知道我做错了什么吗?

解决方案

我是要点的作者.该代码一直有效,直到 express-session 开始强制签名 cookie 并开始以不同的方式实现它们.

我已经更新了要点以使用最新版本的 express-session.为方便起见,以下是要点的副本:

app.js:

var express = require('express'),app = express(),cookieParser = require('cookie-parser'),session = require('express-session'),RedisStore = require('connect-redis')(session);app.use(express.static(__dirname + '/public'));app.use(function(req, res, next) {if (~req.url.indexOf('favicon'))返回 res.send(404);下一个();});app.use(cookieParser());app.use(会话({商店:新的RedisStore({//这是 redis-session-php 使用的默认前缀前缀:'会话:php:'}),//使用默认的 PHP 会话 cookie 名称name: 'PHPSESSID',秘密:'node.js 规则',重新保存:假,保存未初始化:假}));app.use(function(req, res, next) {req.session.nodejs = '来自 node.js 的你好!';res.send('<pre>' + JSON.stringify(req.session, null, ' ') + '</pre>');});应用程序听(8080);

app.php:

<?php//这必须与 Express 应用程序中的 express-session `secret` 匹配定义('EXPRESS_SECRET','node.js 规则');//==== 开始快速会话兼容性 ====//这个 id mutator 函数有助于确保我们查找//使用正确 id 的会话定义('REDIS_SESSION_ID_MUTATOR','express_mutator');函数 express_mutator($id) {if (substr($id, 0, 2) === "s:")$id = substr($id, 2);$dot_pos = strpos($id, ".");如果($dot_pos !== 假){$hmac_in = substr($id, $dot_pos + 1);$id = substr($id, 0, $dot_pos);}返回 $id;}//检查现有的 express-session cookie ...$sess_name = session_name();如果(isset($_COOKIE[$sess_name])){//这里我们必须操作 cookie 数据以便//redis 中的查找工作正常//由于 express-session 现在强制签署 cookie,我们有//在这里处理...if (substr($_COOKIE[$sess_name], 0, 2) === "s:")$_COOKIE[$sess_name] = substr($_COOKIE[$sess_name], 2);$dot_pos = strpos($_COOKIE[$sess_name], ".");如果($dot_pos !== 假){$hmac_in = substr($_COOKIE[$sess_name], $dot_pos + 1);$_COOKIE[$sess_name] = substr($_COOKIE[$sess_name], 0, $dot_pos);//https://github.com/tj/node-cookie-signature/blob/0aa4ec2fffa29753efe7661ef9fe7f8e5f0f4843/index.js#L20-L23$hmac_calc = str_replace("=", "", base64_encode(hash_hmac('sha256', $_COOKIE[$sess_name], EXPRESS_SECRET, true)));如果 ($hmac_calc !== $hmac_in) {//cookie数据已被篡改,可自行判断//你想如何处理这个.对于这个例子,我们将//忽略 cookie 并生成一个新会话 ...未设置($_COOKIE[$sess_name]);}}} 别的 {//让 PHP 为我们生成一个新的 idsession_regenerate_id();$sess_id = session_id();$hmac = str_replace("=", "", base64_encode(hash_hmac('sha256', $sess_id, EXPRESS_SECRET, true)));//根据 express-session 签名的 cookie 格式对其进行格式化session_id("s:$sess_id.$hmac");}//==== 结束快速会话兼容性 ====require('redis-session-php/redis-session.php');RedisSession::start();$_SESSION["php"] = "你好来自 PHP";如果 (!isset($_SESSION["cookie"]))$_SESSION["cookie"] = array();echo "

";回声 json_encode($_COOKIE, JSON_PRETTY_PRINT);回声 json_encode($_SESSION, JSON_PRETTY_PRINT);echo "</pre>";?>

I want to share the server session between a NodeJs app and a PHP app using Redis. I took most of the code from this gist.

NodeJs code:

app.use(session({
    store: new RedisStore({prefix: 'session:php:'}),
    name: 'PHPSESSID',
    secret: 'node.js'
}));

app.use(function(req, res, next) {
    req.session.nodejs = 'node.js!';
    res.send(JSON.stringify(req.session, null, '  ') );

});

And it outputs:

{
    "cookie": {
        "originalMaxAge": null,
        "expires": null,
        "httpOnly": true,
        "path": "/"
    },
    "passport": {},
    "nodejs": "node.js!"
}

PHP code (I use redis-session-php and Predis) :

require('redis-session-php/redis-session.php');
RedisSession::start();

$_SESSION['php'] = 'php';

if (!isset($_SESSION["cookie"])) {
    $_SESSION["cookie"] = array();
}

var_dump($_SESSION);

And it outputs:

array(2) {
    ["php"] => string(3) "php"
    ["cookie"] => array(0) { }
}

The problem: I would expect both sessions to look the same, but they don't ( the app is run on the same domain ). Setting the values with set() from PredisClient works (but the values won't be on the session variable). I found this code that I think would work, using set() and get(), but I feel that it would overcomplicate the code.

Do you know what I am doing wrong?

解决方案

I'm the author of the gist. The code worked until express-session started forcing signed cookies and started implementing them in a different way.

I have updated the gist to work with the latest version of express-session. A copy of the gist follows for convenience:

app.js:

var express = require('express'),
    app = express(),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    RedisStore = require('connect-redis')(session);

app.use(express.static(__dirname + '/public'));
app.use(function(req, res, next) {
  if (~req.url.indexOf('favicon'))
    return res.send(404);
  next();
});
app.use(cookieParser());
app.use(session({
  store: new RedisStore({
    // this is the default prefix used by redis-session-php
    prefix: 'session:php:'
  }),
  // use the default PHP session cookie name
  name: 'PHPSESSID',
  secret: 'node.js rules',
  resave: false,
  saveUninitialized: false
}));
app.use(function(req, res, next) {
  req.session.nodejs = 'Hello from node.js!';
  res.send('<pre>' + JSON.stringify(req.session, null, '    ') + '</pre>');
});

app.listen(8080);

app.php:

<?php
// this must match the express-session `secret` in your Express app
define('EXPRESS_SECRET', 'node.js rules');

// ==== BEGIN express-session COMPATIBILITY ====
// this id mutator function helps ensure we look up
// the session using the right id
define('REDIS_SESSION_ID_MUTATOR', 'express_mutator');
function express_mutator($id) {
  if (substr($id, 0, 2) === "s:")
    $id = substr($id, 2);
  $dot_pos = strpos($id, ".");
  if ($dot_pos !== false) {
    $hmac_in = substr($id, $dot_pos + 1);
    $id = substr($id, 0, $dot_pos);
  }
  return $id;
}
// check for existing express-session cookie ...
$sess_name = session_name();
if (isset($_COOKIE[$sess_name])) {
  // here we have to manipulate the cookie data in order for
  // the lookup in redis to work correctly

  // since express-session forces signed cookies now, we have
  // to deal with that here ...
  if (substr($_COOKIE[$sess_name], 0, 2) === "s:")
    $_COOKIE[$sess_name] = substr($_COOKIE[$sess_name], 2);
  $dot_pos = strpos($_COOKIE[$sess_name], ".");
  if ($dot_pos !== false) {
    $hmac_in = substr($_COOKIE[$sess_name], $dot_pos + 1);
    $_COOKIE[$sess_name] = substr($_COOKIE[$sess_name], 0, $dot_pos);

    // https://github.com/tj/node-cookie-signature/blob/0aa4ec2fffa29753efe7661ef9fe7f8e5f0f4843/index.js#L20-L23
    $hmac_calc = str_replace("=", "", base64_encode(hash_hmac('sha256', $_COOKIE[$sess_name], EXPRESS_SECRET, true)));
    if ($hmac_calc !== $hmac_in) {
      // the cookie data has been tampered with, you can decide
      // how you want to handle this. for this example we will
      // just ignore the cookie and generate a new session ...
      unset($_COOKIE[$sess_name]);
    }
  }
} else {
  // let PHP generate us a new id
  session_regenerate_id();
  $sess_id = session_id();
  $hmac = str_replace("=", "", base64_encode(hash_hmac('sha256', $sess_id, EXPRESS_SECRET, true)));
  // format it according to the express-session signed cookie format
  session_id("s:$sess_id.$hmac");
}
// ==== END express-session COMPATIBILITY ====



require('redis-session-php/redis-session.php');
RedisSession::start();

$_SESSION["php"] = "Hello from PHP";
if (!isset($_SESSION["cookie"]))
  $_SESSION["cookie"] = array();

echo "<pre>";
echo json_encode($_COOKIE, JSON_PRETTY_PRINT);
echo json_encode($_SESSION, JSON_PRETTY_PRINT);
echo "</pre>";

?>

这篇关于如何使用Redis在NodeJs和PHP之间共享会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:自动打开 PDF 文件的打印机对话框 下一篇:连接到 Redis 以使用 PHP

相关文章