首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有在交叉子域上设置Httponly cookie。

没有在交叉子域上设置Httponly cookie。
EN

Stack Overflow用户
提问于 2022-01-25 11:03:08
回答 1查看 439关注 0票数 1

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

它返回“由于它的域属性对于当前主机url"无效,所以这个Set-Cookie被阻塞了。

下面是我的后端代码:

代码语言:javascript
复制
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-前端}.herokuapp.com登录:

代码语言:javascript
复制
fetch('https://{my-backend}.herokuapp.com/login', {
  method: 'POST', credentials: 'include'
});

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

代码语言:javascript
复制
fetch('https://{my-backend}.herokuapp.com/protect-me', {
  credentials: 'include'
});

谢谢你的注意:)

附加说明

顺便提一句,当我们有根域和子域通信时,这非常好,我的意思是,例如,如果您的auth服务器在yourdomain.com上,那么您的仪表板在dashboard.yourdomain.com上,那么您可以很容易地设置一个.yourdomain.com cookie,并且所有的操作都很好。

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

EN

回答 1

Stack Overflow用户

发布于 2022-01-25 12:23:26

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70847527

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档