【问题标题】:isAuthenticated() returns false after successful redirectisAuthenticated() 重定向成功后返回 false
【发布时间】:2020-04-12 02:38:11
【问题描述】:

在离开后端端口:5000 并重定向到端口:3000(我的前端主页)后,我可以得出结论,身份验证会话停止。

我在做什么: 单击登录到 google 按钮,使用良好帐户登录,重定向到我的前端主页,在该主页运行获取请求并获取登录的用户个人资料信息。

我正在使用带有 passport.js 的 google oAuth 登录。 Mongoose 保存会话和用户配置文件信息。 req.isAuthenticated() 在所有路由上都应该等于 true,直到注销。而是一切正常,直到我 res.redirect 到前端主页的最后一点。

app.get(
  "/auth/google",
  passport.authenticate("google", { scope: ["profile", "email"] })
);

app.get(
  "/auth/google/login",
  passport.authenticate("google", { failureRedirect: "/new" }),
  (req, res) => {
    console.log(` Authentication Status: ${req.isAuthenticated()}`); // READS AS TRUE
    console.log(` User? : ${req.user}`); /// SHOWS USER INFO
    console.log("end of user status before redirect.");
    res.redirect("http://localhost:3000/");
  }
);

问题:

在最后一个函数上,我可以说一切正常,直到 res.redirect。除非我输入命令 req.logout() 它应该能够跟踪我的会话,并且在后端 req.isAuthenticated 应该等于 true。相反,在我有条件设置 req.isAuthenticated 的其他路线中,读数为假。

// quick fetch request I run on front end to show user as logged in and profile info.
app.get("/getuser", (req, res) => {
  console.log("user CHECK :", req.user); // READS UNDEFINED HERE
  console.log(`is authenticated:`, req.isAuthenticated()); // READS FALSE HERE
  if (req.isAuthenticated()) {
    const user = req.user;
    console.log("user:", req.user);
    res.json({ user: user, isAuthenticated: true });
  } else {
    const user = false;
    console.log("user:", req.user);
    res.json({ user: false, isAuthenticated: false });
  }
});

它变得陌生了......

我的浏览器接收到 connect.sid cookie,我的数据库保存了用户和会话。

来自本地主机上的 chrome 浏览器 cookie:

从我的数据库中的会话创建的已保存帐户的屏幕截图

我已经检查了很多 Stack Overflow 线程。他们似乎都没有帮助我。

【问题讨论】:

    标签: javascript authentication oauth-2.0 passport.js session-cookies


    【解决方案1】:

    我的事件与端口有关,而不是会话。我的 react 应用程序在端口 3000 上运行,方法是使用语法 "proxy":"http://localhost:5000" 在我的 package.json 文件中设置代理,我能够获取所有路由并将它们转换为我的快速路由,然后返回其授权的重定向 url。

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 1970-01-01
      • 2021-01-28
      • 2014-04-28
      • 2021-01-24
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2014-04-16
      相关资源
      最近更新 更多