gpt4 book ai didi

node.js - 未设置安全 cookie

转载 作者:行者123 更新时间:2023-12-04 01:15:59 25 4
gpt4 key购买 nike

如果我从 Netlify 进行 api 调用,我似乎无法设置 cookie,但使用 Postman 就可以了。

我不明白为什么。

我的代码是这样的:

router.post('/login', localAuth, async (req, res) => {
// The code goes through and returns status 200
return res.status(200)
.cookie('accessToken', accessToken, {
signed: true,
httpOnly: true,
secure: true,
maxAge: 15 * 60 * 1000,
sameSite: 'none', // <-- I also tried lax
}).cookie('refreshToken', refreshToken, {
signed: true,
httpOnly: true,
secure: true,
maxAge: 7 * 24 * 60 * 60 * 1000,
sameSite: 'none', // <-- I also tried lax
}).send( // something );
});

然后代码尝试不同的路由,之后由于缺少 cookie 而失败

router.get('/user', accessjwtAuth <-- this fails due to no cookies, async (req, res) => {})

Netlify 默认自带 SSL 证书。来自前端的调用如下所示:

const config = {
baseURL: `${API_URL}/api/auth/login`,
method: 'post',
withCredentials: true,
headers: {'Content-Type': 'application/json',},
data: values,
};
axios(config).then((res) => {});

最后,express 应用配置如下:

const allowed_origins = ["https://something.netlify.app", "localhost:8080"];
app.use(function(req, res, next) {
const origin = req.headers.origin;
if (allowed_origins.indexOf(origin) > -1) {
res.setHeader('Access-Control-Allow-Origin', origin);
};
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
next();
});

我不断为我的 signedcookies 获取这个,[Object: null prototype] {}

我注意到这个问题发生在 Safari 而不是 Chrome。在 Chrome 中,请求同时具有 accessTokenrefreshToken。我还注意到,如果我设置 sameSite: 'lax',那么只会保留 refreshToken

最佳答案

From MDN

Browsers are migrating to have cookies default to SameSite=Lax. If a cookie is needed to be sent cross-origin, opt out of the SameSite restriction by using the None directive. The None directive requires that the Secure attribute also be used.

您在 Chrome 上的操作是正确的(通过设置 sameSite=Nonesecure=true)

对于Safari with its major update to Safari Intelligent Tracking Prevention (ITP) ,我认为我们必须手动启用跨站点跟踪首选项。我认为您可以告诉您的用户这样做,或者尝试想出另一种方法来在没有跨站点 cookie 的情况下实现该功能。

关于node.js - 未设置安全 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63364879/

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