Express-Session 在生产/部署中不起作用

问题描述 投票:0回答:5

Express-Session 正在开发环境中工作,因为它在我的浏览器中设置了“connect.sid”cookie。然而,在生产中它不会存储 cookie,并且不会使用相同的会话 - 它每次都会创建一个新会话。我相信,如果我能以某种方式保存第三方 cookie,这个问题就会得到解决,因为我的应用程序是使用 Heroku 部署的。最后,我还使用了express-cors来避免CORS问题(不知道这是否与cookie问题有关)。我在 cors 中设置了 {credentials: true},在 Axios 中也设置了 {withCredentials: true}。

node.js axios express-session third-party-cookies
5个回答
4
投票

Heroku 使用反向代理。它提供 https 端点,但随后将未加密的流量转发到网站。

尝试类似的事情

app.enable('trust proxy')

并查看 https://expressjs.com/en/guide/behind-proxies.html


2
投票

问题解决了! -> 添加相同站点:'无' 用于生产的完整 Cookie 配置(快速会话):

cookie:{ httpOnly:正确, 安全:真实, 最大年龄:1000 * 60 * 60 * 48, 同一站点:“无” }


2
投票

向会话配置添加“名称”属性对我有用:

{
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    proxy: true, // Required for Heroku & Digital Ocean (regarding X-Forwarded-For)
    name: 'MyCoolWebAppCookieName', // This needs to be unique per-host.
    cookie: {
      secure: true, // required for cookies to work on HTTPS
      httpOnly: false,
      sameSite: 'none'
    }
  }

1
投票

对我有用的代码。你必须添加

app.set("trust proxy", 1);

sameSite: "none" // this option in cookie object

整个代码如下所示。

app.set("trust proxy", 1); // trust first proxy

app.use(
  session({
    secret: config.domain,
    store: new SequelizeStore({
      db: db.sequelize,
      checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions in milliseconds.
      expiration: 15 * 24 * 60 * 60 * 1000, // The maximum age (in milliseconds) of a valid session.
    }),
    resave: false, // we support the touch method so per the express-session docs this should be set to false
    proxy: true, // if you do SSL outside of node.
    saveUninitialized: true,
    cookie: { secure: true, sameSite: "none" },
  })
);

0
投票

我的服务器部署在AWS ALB和CloudFront后面。除了上面的配置之外,我还必须在CloudFront中转发cookie。

© www.soinside.com 2019 - 2024. All rights reserved.