我已经创建了两个herokuapps,它们都共享herokuapp.com作为主域,但是当我想将cookie从一个设置到另一个时,它不允许我使用ngrok进行测试,结果是一样的。
它返回“由于它的域属性对于当前主机url"无效,所以这个Set-Cookie被阻塞了。
下面是我的后端代码:
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登录:
fetch('https://{my-backend}.herokuapp.com/login', {
method: 'POST', credentials: 'include'
});然后从{my-前端}.herokuapp.com发出第二个请求:
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也可以访问它。
发布于 2022-01-25 12:23:26
我认为cookie域应该与前端url相同,这也是错误的意思。
https://stackoverflow.com/questions/70847527
复制相似问题