【问题标题】:Httponly cookie is not set on cross subdomain未在跨子域上设置 Httponly cookie
【发布时间】:2023-04-04 16:57:01
【问题描述】:

我创建了 2 个 herokuapps,都共享 herokuapp.com 作为主域,但是当我想将 cookie 从一个设置到另一个时它不允许我,我也用 ngrok 测试了它,结果是一样的。

返回“此 Set-Cookie 被阻止,因为它的域属性对于当前主机 url 无效”

这是我的后端代码:

const express = require("express");
const app = express();
const cors = require("cors");
const cookieParser = require("cookie-parser");

app.use(cookieParser());

app.use(
  cors({
    origin: [process.env.FRONT_URL], // {my-frontend}.herokuapp.com
    methods: ["GET", "PUT", "POST"],
    allowedHeaders: ["Content-Type", "Authorization", "x-csrf-token"],
    credentials: true,
    maxAge: 600,
    
    exposedHeaders: ["*", "Authorization"],
  })
);

app.get(
  "/protect-me",
  function (req, res, next) {
    if (req.cookies["access_token"] == "accesstoken") next();
    else return res.status(401).send("Unauthorized");
  },
  function (req, res, next) {
    res.json({ msg: "user get" });
  }
);


app.post("/login", function (req, res, next) {
  res.cookie("access_token", "accesstoken", {
    expires: new Date(Date.now() + 3600 * 1000 * 24 * 180 * 1), //second min hour days year
    secure: true, // set to true if your using https or samesite is none
    httpOnly: true, // backend only
    sameSite: "none", // set to none for cross-request
    domain: process.env.COOKIE_DOMAIN, // tested both with .herokuapp.com & herokuapp.com
    path: "/"
  });

  res.json({ msg: "Login Successfully" });
});

app.listen(process.env.PORT, function () {
  console.log("CORS-enabled web server listening on port 80");
});

然后在前端我首先尝试使用来自 {my-frontend}.herokuapp.com 的代码登录:

fetch('https://{my-backend}.herokuapp.com/login', {
  method: 'POST', credentials: 'include'
});

然后从 {my-frontend}.herokuapp.com 发出第二个请求:

fetch('https://{my-backend}.herokuapp.com/protect-me', {
  credentials: 'include'
});

提前感谢您的关注:)

补充说明

顺便说一句,当我们有根域和子域通信时,这非常有效,我的意思是,例如,如果您的身份验证服务器位于yourdomain.com,那么您的仪表板位于dashboard.yourdomain.com ,然后您可以轻松设置.yourdomain.com cookie,一切正常

但我不可能用auth.yourdomain.com.yourdomain.com 制作一个cookie,以便dashboard.yourdomain.com 也可以访问它

【问题讨论】:

    标签: javascript node.js cookies httponly cookie-httponly


    【解决方案1】:

    我认为 cookie 域应该与前端 url 的域相同,这也是错误的意思

    【讨论】:

    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 2015-05-28
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    相关资源
    最近更新 更多