You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node+Passport JS+cookie-session部署后客户端无法获取会话数据

我本地用开发服务器运行基于Node、Passport JS和cookie-session的项目时,所有功能都正常。但把客户端和后端部署到线上后,出现了客户端无法从Cookie中读取会话数据的问题。我检查了前后端的Cookie,确认session和session.sig完全一致,但问题还是没解决。

后端代码:

server.js:

dotenv.config({ path: "./.env" });
const cookieKey = process.env.COOKIE_KEY;
const express = require("express");
const cookieSession = require("cookie-session");
const connectDB = require("./config/db");
const passport = require("passport");
const PORT = process.env.PORT || 4500;
const cors = require("cors");

connectDB();

const app = express();
//middleware
app.use(express.json());
app.use(
  cors({
    origin: true, // replace with your frontend domain
    credentials: true,
  })
);

app.use(
  cookieSession({
    maxAge: 24 * 60 * 60 * 1000, // 1 day
    keys: [cookieKey],
    cookie: {
      secure: true,
      sameSite: "none",
    },
  })
);

app.use(passport.initialize());
app.use(passport.session());

const authentication = require("./routes/Authentication.js");
app.use("/api/v1/auth", authentication);

const tabs = require("./routes/Tabs.js"); // Adjust the path as necessary
app.use("/api/v1/tabs", tabs);

const preferences = require("./routes/Preferences.js");
app.use("/api/v1/preferences", preferences);

const google = require("./routes/Google.js"); // Adjust the path as necessary
app.use("/api/v1/google", google);
app.listen(PORT, () => console.log("Server is connected"));

authentication.js:

dotenv.config({ path: "./.env" });
const sucessRedirectURL = process.env.SUCCESS_REDIRECT_URL;
const express = require("express");
const passport = require("passport");
require("../services/Passport");
const router = express.Router();

router.get(
  "/google",
  passport.authenticate("google", {
    scope: ["profile", "email", "https://www.googleapis.com/auth/calendar"],
    accessType: "offline",
    approvalPrompt: "force",
  })
);

router.get(
  "/google/callback",
  passport.authenticate("google", {
    successRedirect: sucessRedirectURL,
  })
);

router.get("/me", (req, res) => {
  if (req.user) {
    res.send(req.user);
  } else {
    res.status(401).json({ message: "Not authenticated" });
  }
});

router.get("/logout", (req, res) => {
  console.log("logging out");
  req.logout();
  res.redirect("/");
});

module.exports = router;

passport.js:

dotenv.config({ path: "./.env" });
const googleClientID = process.env.GOOGLE_CLIENT_ID;
const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET;
const backendAppURL = process.env.BACKEND_APP_URL;

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20");
const User = require("../models/User");

//when a user logs in, we get a 'user object' which is serialized to our session by storing a user's ID,
//which is called automatically after logging
passport.serializeUser((user, done) => {
  done(null, user.id);
});
//now, when we want to take the data stored in our session, we use the ID to recreate the full user object on
//each request, which is automatically done on each request
passport.deserializeUser((id, done) => {
  User.findById(id).then((user) => {
    done(null, user);
  });
});
//this code happens first to find/create a user object
passport.use(
  new GoogleStrategy(
    {
      clientID: googleClientID,
      clientSecret: googleClientSecret,
      callbackURL: backendAppURL + "/api/v1/auth/google/callback", //FULL CALLBACK URL IN PRODUCTION VS RELATIVE PATH IN DEVELOPMENT
    },
    async (accessToken, refreshToken, profile, done) => {
      try {
        const existingUser = await User.findOneAndUpdate(
          { googleId: profile.id },
          {
            accessToken,
            refreshToken,
            name: profile.displayName,
            avatarUrl: profile.picture,
            isVerified: profile.emails[0].verified,
          }
        );

        if (existingUser) {
          console.log("Existing user found:", existingUser);

          return done(null, existingUser);
        }

        const user = await new User({
          accessToken,
          refreshToken,
          name: profile.displayName,
          email: profile.emails[0].value,
          googleId: profile.id,
          avatarUrl: profile.picture,
          isVerified: profile.emails[0].verified,
        }).save();
        console.log("New user saved:", user);

        done(null, user);
      } catch (error) {
        console.error("Error during authentication: ", error);
        done(error);
      }
    }
  )
);

后端Cookie截图:

后端Cookie

内容的提问来源于stack exchange,提问作者sweglord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:29:57