安全的cookies未设置

3
我似乎无法在从Netlify进行API调用时设置cookies,但使用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会被保留。


也许您可以尝试在Safari中启用“跨站点跟踪”,以查看问题是否出在它上面。 - dongnhan
那真的起作用了。Safari和Chrome都成功登录并保留了它们的令牌以供下一次API调用使用。但我不能期望用户去更改这个设置,所以我该从哪里入手来解决呢?终于有东西可以用了,谢谢。 - Joseph K.
1个回答

5

来自MDN

浏览器正在迁移到默认使用SameSite=Lax的cookie。如果需要发送跨源cookie,请使用None指令退出SameSite限制。None指令要求还使用Secure属性。

您可以通过设置sameSite=Nonesecure=true来正确处理Chrome。

对于Safari以其重大更新的Safari Intelligent Tracking Prevention (ITP), 我认为我们必须手动启用跨站点跟踪偏好设置。您可以告诉用户进行设置或尝试另一种方法来实现没有跨站点cookie的功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接