跨子域共享Express会话

时间:2019-09-01 10:08:10

标签: node.js express session passport.js express-session

我有2个应用程序,即WEB和APP,它们分别位于不同的端口(本地)和不同的域(公共)上,例如:

  1. www.domain.com(WEB)
  2. app.domain.com(APP)

我试图在两个应用程序上调用相同的登录会话,我在本地计算机上运行的代码效果很好(也许是因为其相同的主机名和端口不会中断该会话并将其计为一个新的会话)

当我尝试将代码推送到生产环境中时,它根本无法工作,网络会话无法识别由APP设置的会话

APP是设置会话的地方(它处理登录)。

下面的session和cors代码在网络和应用程序上都使用

const cors = require('cors')
app.use(cors());
app.use(cookieParser());

app.use(
    session({
        resave: true,
        saveUninitialized: true,
        secret: process.env.SESSION_SECRET,
        cookie: { maxAge: 1209600000 }, // two weeks in milliseconds
        store: new MongoStore({
            mongooseConnection: mongoose.connection,
            autoReconnect: true
        })
    })
);

一旦用户从APP登录,我希望该会话可以通过WEB软件包进行维护和调用。这样我也可以动态更改网站体验。

解决方案

@theusguy关于添加域参数是正确的。我面临的其他问题有待解决

Headers.Host 我的nginx配置不正确,因此主机名是127.0.0.1:3000 修复我将以下配置添加到conf

location / {
proxy_pass http://127.0.0.1:3021;
proxy_http_version 1.1; //this was missing
proxy_set_header Upgrade $http_upgrade; //this was missing
proxy_set_header Connection 'upgrade'; //this was missing
proxy_set_header Host $host; //this was missing
proxy_cache_bypass $http_upgrade; //this was missing
}

继续前进,app.js的流程很重要

APP

var app = express();
app.enable('trust proxy');
// app.use(cors()); //APP does not need cors because its GENERATING the long lasting session that needs to be read everywhere
//Everything else goes below this
app.use(cookieParser());
app.use(
    session({
        resave: false,
        saveUninitialized: false,
        secret: process.env.SESSION_SECRET,
        cookie: {
            domain: '.domain.com',
            maxAge: 1209600000 // two weeks in milliseconds
        },
        store: new MongoStore({
            mongooseConnection: mongoose.connection,
            autoReconnect: true
        })
    })
);

var mainRouter = require('./routes/main');

网络

var app = express();
app.enable('trust proxy'); 
app.use(cors()); // TO read the cookie being set from elsewhere
var mainRouter = require('./routes/main');

最后

我必须清除我的Cookie ,以删除任何误报 ^这是最烦人的步骤

1 个答案:

答案 0 :(得分:0)

这可能是由于在子域级别设置了Cookie。 app.domain.com(app)的会话cookie不适用于www.domain.com(WEB)。

尝试更改代码以在域级别设置Cookie,然后查看是否可行。

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var str = doc.getBody().getText();//modified
  var search = "f";
  var regx = new RegExp("(.)"+search+"(.)")
  var y = regx.exec(str);
  Logger.log(y);
  if (y !== null){ Logger.log("Previous character" + y[1]).log("Next character:" + y[2])}
}