【问题标题】:Express not setting HTTPOnly cookie in productionExpress 不在生产环境中设置 HTTPOnly cookie
【发布时间】:2021-06-21 04:36:00
【问题描述】:

我正在使用带有会话 cookie 的 firebase 来对我的 react 网站上的用户进行身份验证。后端使用谷歌云功能。当我在本地主机上登录我的网站时,一切正常;我的 React 应用程序在 localhost:3000 上运行,我的云功能在 locahost:5000 上运行。我的初始化代码如下所示:

app.use(cors({credentials: true, origin: ['http://localhost:3000', 'https://beta.example.com','https://example.com']}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
  }));

app.use(cookieParser());

登录代码如下所示:

const idToken = req.body.idToken.toString();

  // Set session expiration to 5 days.
  const expiresIn = 60 * 60 * 24 * 5 * 1000;
  admin
    .auth()
    .createSessionCookie(idToken, { expiresIn })
    .then((sessionCookie) => {
      const options = { maxAge: expiresIn, httpOnly: true, secure: false };
      res.cookie("session", sessionCookie, options);
      return res.json({ message: "Logged in!" });
    })
    .catch((err) => {
      console.log(err);
      return res
        .status(403)
        .json({ general: "Wrong credentials, please try again" });
    });
};

问题似乎是跨域的,因为我的网站托管在谷歌云功能之外的另一个域上,无论我尝试什么都无法设置 cookie。我尝试使用 axios 并获取请求,它们都在本地主机上工作。这是从我的前端获取的:

fetch(api_url + "/login", {
        method: "POST",
        redirect: "follow",
        credentials: "include", // Don't forget to specify this if you need cookies
        headers: headers,
        body: JSON.stringify({
          idToken: idToken,
        }),
      }).then((res) => {
        console.log("LOGGED IN!!!", res.data);
        dispatch(getuserData(true, history, url));
      });

我可以在使用 localhost 时看到名为“session”的 cookie,它正在按应有的方式创建;当我按下我网站上的登录按钮时。在我的自定义域上按相同的登录按钮时,此 cookie 不存在

快速说明,后端并没有崩溃,只是由于某种原因它没有将 cookie 保存在服务器上

【问题讨论】:

    标签: node.js express firebase-authentication google-cloud-functions session-cookies


    【解决方案1】:

    Cookie 不提供端口隔离。如果运行在一个端口上的服务可以读取 cookie,那么运行在同一服务器的另一个端口上的服务也可以读取 cookie。

    这就是原因。当您在本地工作时,您的前端和后端 api 都属于 localhost 域。

    在生产环境中,您可能会在不同的端点上部署前端和后端 API。 对于 SPA 应用程序,我建议使用 localStorage 而不是 cookie。

    【讨论】:

    • 是的,这也是我在帖子中所说的,问题是跨域 cookie。
    • 前端和后端部署在不同的域上是没有办法解决的。如果您仍想使用 cookie,常见的方法是通过 /api 之类的子路由为您的后端创建代理,但它应该是另一个主题。
    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 2011-04-14
    • 1970-01-01
    • 2022-01-14
    • 2023-04-09
    • 1970-01-01
    • 2015-05-30
    • 2015-04-04
    相关资源
    最近更新 更多