我在 Heroku 中托管了前端和后端。
我正在尝试实现 Google 身份验证。从 Google OAuth2 获取 token 后,我尝试设置
id_token
以及通过 express 应用程序在 cookie 中的用户详细信息。下面是我在后端的一段代码,
authRouter.get('/token', async (req, res) => {
try {
const result = await getToken(String(req.query.code))
const { id_token, userId, name, exp } = result;
const cookieConfig = { domain: '.herokuapp.com', expires: new Date(exp * 1000), secure: true }
res.status(201)
.cookie('auth_token', id_token, {
httpOnly: true,
...cookieConfig
})
.cookie('user_id', userId, cookieConfig)
.cookie('user_name', name, cookieConfig)
.send("Login succeeded")
} catch (err) {
res.status(401).send("Login failed");
}
});
它在我的本地非常适合我,但它不适用于 heroku。
这些是我已经尝试过的域 -
.herokuapp.com
herokuapp.com
.另外,我在没有指定域字段本身的情况下进行了尝试。我可以看到
Set-Cookie
响应 header 的详细信息,但/token 端点失败而没有返回任何状态代码,我看不到应用程序选项卡上设置的 cookie。请看下面的图片,
我在这里看不到任何状态代码,但它说它失败了。
这些是我可以看到的 cookie 信息,但如果我通过应用程序选项卡检查,则不可用。
我在这里错过了什么?有人可以帮助我吗?
最佳答案
可能你应该尝试安全:secure: req.secure || req.headers['x-forwarded-proto'] === 'https'
关于node.js - 无法从 Heroku 上托管的 Express 应用程序设置 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62106113/