首页 > 解决方案 > 来自快速会话的会话不会通过请求持续存在

问题描述

我正在使用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属性)。我错过了什么吗?

标签: expresssessionexpress-session

解决方案


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


推荐阅读