【发布时间】: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