gpt4 book ai didi

node.js - 跨域应用程序的快速 session 不发送 cookie

转载 作者:行者123 更新时间:2023-12-05 04:46:16 31 4
gpt4 key购买 nike

设置

后端:Express.js、express-session、connect-mongo、cors、在 Heroku(免费版)的 Node.js 主机中运行的模块,以及将数据存储到 MongoDB Atlas(基于云的Mongo解决方案)

前端:React.js、axios,在 Godaddy 共享 linux 主机上工作。

我使用 Heroku 免费域 ( https://app-name.herokuapp.com ),以及为 Godaddy 购买的域。

此外,对于免费的 HTTPS 证书,我使用 Cloudflare(免费版)。

问题

前端和后端之间的通信运行良好。发送和接收数据。但是,在我需要实现的登录系统中,数据被发送,正确地通过了数据库检查,之后,我将 session 保存到数据库中。它运行良好,直到 COOKIE 设置部分,当我在前端域中没有收到 session cookie 时。

代码

app.js

// In my app.js, the entry point for backend
// ---> This line is just after module importing.

dotenv.config();

const storage = new store({
mongoUrl: ""+process.env.MONGODB_URI, collectionName: "sessions", ttl: 100, autoRemove: "native"
});

app.disable("X-Powered-By");

app.use(cors({origin: "https://my.godaddy.subdomain", credentials: true, methods: "GET, POST, PUT, DELETE"}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", "https://my.godaddy.subdomain");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-HTTP-Method-Override");
res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
next();
});

// "my.godaddy.subdomain" is the SUBDOMAIN where i have an Administrators' login page, so it is separated from public site "godaddy.subdomain" (ONLY FOR EXAMPLE PURPOSE)

app.use(express.json());
app.use(express.urlencoded({extended: false}));

mongo.connect(""+process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "Test_DB"
}
).then(() => console.log("Connected to MongoDB!"))
.catch((err) => console.log("Error connecting to MongoDB: "+err));

app.use(session({
name: "admin_session",
secret: ""+process.env.SERVER_SECRET,
resave: true,
rolling: false,
saveUninitialized: false,
unset: "destroy",
cookie: {
sameSite: "none", // I tried changing this a thousand times, no result...
secure: true, // The maximum i could was set a session sucessfully IN THE HEROKU
httpOnly: true, // BACKEND (no cross-domain), but that would be useless...
maxAge: 8600000
},
store: storage
}));

// ---> After this line, the routing code, all working fine.

admin_routing.js

// The Admin route, called admin_routing.js, used in app.js

router.route("/admin/login").post(async (req, res, next) =>
{
const {username, password} = req.body;
const admin = await Admin.find({user_login: username}).then((doc) => doc.pop());

if(admin.user_login === username)
{
await bcrypt.compare(password, admin.user_pass).then((same) =>
{
if(same)
{
req.session.adminID = admin._id;
req.session.save((err) => console.log(err)); // here i save the session
console.log(req.body, req.session); // it is sucessfully saved but
res.send({error: "Sucess!"}); // NO COOKIE IS SENT...
}
else
{
res.send({error: "Check your credentials and try again."});
}
});
}
else
{
res.send({error: "No administrators found."});
}
});

前端请求(登录组件)

// The part of my frontend where i post login data, in a React.js Component

await axios.post("https://my-app.herokuapp.com/admin/login",
{username: Inputs[0].value, password: Inputs[1].value}, {withCredentials: true, method: "POST",
headers: {'Access-Control-Allow-Origin': 'https://my-app.herokuapp.com'}})
.then((res) =>
{
document.getElementById("err-bc").innerText = ""+res.data.error; // Design purpose
document.getElementById("err-bc").style.visibility = "visible";
console.log(res.data);
}).catch((err) =>
{
document.getElementById("err-bc").innerText = ""+res.data.error; // Design purpose
document.getElementById("err-bc").style.visibility = "visible";
});

修复后应该如何工作

它必须保存 session ,将 cookie 发送回我的子域中的前端,并且当登录的 ADMIN 用户转到公共(public)页面时,它必须仍然保留 cookie 以进行身份​​验证。因此 adm.mydomain.com 收到身份验证 cookie,并在用户访问 mydomain.com 和 www.mydomain.com 时保留它。 (公共(public)页面)。

希望有人有答案,现在我已经尝试解决了两天。

谢谢。

最佳答案

所以,几个小时后...

自己问题的解决方案

在使用非快速 session cookie、来自 Express 的本地 res.cookie() 并启用“信任代理”进行一些测试后,我解决了问题并且现在可以正常工作了!

变化:

app.js

// In my app.js, the entry point for backend
// ---> This line is just after module importing.

dotenv.config();

const storage = new store({
mongoUrl: ""+process.env.MONGODB_URI, collectionName: "sessions", ttl: 100, autoRemove: "native"
});

app.disable("X-Powered-By");

app.set("trust proxy", 1); // -------------- FIRST CHANGE ----------------

app.use(cors({origin: "https://my.godaddy.subdomain", credentials: true, methods: "GET, POST, PUT, DELETE"}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", "https://my.godaddy.subdomain");
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, X-HTTP-Method-Override, Set-Cookie, Cookie");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
next();
}); // --------------- SECOND CHANGE -------------------

// "my.godaddy.subdomain" is the SUBDOMAIN where i have an Administrators' login page, so it is separated from public site "godaddy.subdomain" (ONLY FOR EXAMPLE PURPOSE)

app.use(express.json());
app.use(express.urlencoded({extended: false}));

mongo.connect(""+process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "Test_DB"
}
).then(() => console.log("Connected to MongoDB!"))
.catch((err) => console.log("Error connecting to MongoDB: "+err));

app.use(session({
name: "admin_session",
secret: ""+process.env.SERVER_SECRET,
resave: true,
rolling: false,
saveUninitialized: false,
unset: "destroy",
cookie: {
sameSite: "none",
secure: true,
httpOnly: true,
maxAge: 8600000
},
store: storage
}));

// ---> After this line, the routing code, all working fine.

admin_routing.js

// The Admin route, called admin_routing.js, used in app.js

router.route("/admin/login").post(async (req, res, next) =>
{
const {username, password} = req.body;
const admin = await Admin.find({user_login: username}).then((doc) => doc.pop());

if(admin.user_login === username)
{
await bcrypt.compare(password, admin.user_pass).then((same) =>
{
if(same)
{
req.session.adminID = admin._id;
req.session.save((err) => console.log(err));
res.header("Content-Type", "application/json"); // ------- THIRD CHANGE --------
res.send({error: "Sucess!"});
}
else
{
res.send({error: "Check your credentials and try again."});
}
});
}
else
{
res.send({error: "No administrators found."});
}
});

更改后...

现在一旦我登录就会发送 cookie,但是出现了一个新问题:COOKIES 不会在浏览器中持久化但幸运的是,这很容易解决:因为我得到了一个带有我的 API/后端域的 cookie,当我重新加载时它肯定不会保留在我的浏览器中,所以,要解决这个问题只需添加一个 GET再次保存 session 的请求 (req.session.save();),调用每次浏览器刷新或站点打开,并在需要时获取 session 数据。毕竟, session 会持续存在,并且会在前端发出的每个 GET 请求中发送 cookie 时被识别。

代码

admin_router.js

router.route("/auth/check").get(async(req, res, next) => 
// THIS route is called evertime the window refreshs (what is a bit rare in React.js) OR when data is needed (working...)
{
if(req.session.adminID)
{
const admin = await Admin.find({_id: ""+req.session.adminID}).then((doc) => doc.pop());
req.session.save(); //IN THIS PART, cookie is sent back to Frontend again, making the session persist correctly
res.send({hasSession: true, admin: {name: admin.name, picture: admin.user_picture}}); // THIS data is saved to localStorage, since is public data, so i don't need to get it everytime
}
else
{
res.send({msg: "No session started.", hasSession: false});
}
});

仅此而已。希望这可以帮助任何有同样问题的人。祝您好运,如果这对您来说仍然是个问题,请随时将其发布在这里。

谢谢。 :)

关于node.js - 跨域应用程序的快速 session 不发送 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68886973/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com