【问题标题】:Session from express-session not persisting through requests来自快速会话的会话不会通过请求持续存在
【发布时间】:2021-06-04 04:44:11
【问题描述】:

我正在使用 express-session 并尝试使用自定义中间件实现受保护的路由。

[注意:我当前将会话存储在内存中]

app.use(
  session({
    secret: "f4z4gs$Gcg",
    cookie: { maxAge: 300000000, secure: true },
    saveUninitialized: false,
    resave: false,
    store,
  })
);

// MIDDLEWARE
function ensureAuthenticated(req, res, next) {
  console.log(req.session) //  This doesn't show the user and authenticated properties created in the POST login request
  if (req.session.authenticated) {
    return next();
  } else {
    res.status(403).json({ msg: "You're not authorized to view this page" });
  }
};

app.post("/login", (req, res) => {
  const { username, password } = req.body;

  db.users.findByUsername(username, (err, user) => {
    if (user) {
      if (user.password === password) {
        // Add your authenticated property below:
        req.session.authenticated = true;
        // Add the user object below:
        req.session.user = {
          username,
          password,
        };
        // Send the session back to the client below:
        res.json(req.session); // Properties show up here
      } else {
        res.status(403).json({ msg: "Bad Credentials" });
      }
    } else {
      res.status(403).json({ msg: "No user found!" });
    }
  });
});


// PROTECTED ROUTE
app.get("/protected", ensureAuthenticated, (req, res) => {
  res.render("profile");
});

一旦用户成功登录,我会尝试在req.session 中添加两个属性:authenticateduser 对象。但是,一旦我登录并尝试使用中间件访问/protected,我的会话属性就不会持续存在(没有userauthenticated 属性)。我错过了什么吗?

【问题讨论】:

  • 不确定这是否有帮助,但请尝试将 secure 设置为 false。
  • 成功了!不知道为什么。
  • 要添加这是一个解决方案,请将其标记为一个。谢谢!

标签: express session express-session


【解决方案1】:

尝试在 cookie 对象中将 secure 设置为 false。如果您希望它是 httpOnly,那么只需将 httpOnly 设置为 true。

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2016-12-15
    • 2017-12-28
    • 2012-01-10
    • 1970-01-01
    • 2011-10-29
    相关资源
    最近更新 更多