【问题标题】:Secure cookies not being set未设置安全 cookie
【发布时间】:2020-08-15 23:39:31
【问题描述】:

如果我从 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) => {});

最后,快递应用是这样配置的:

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();
});

我一直在为我的已签名cookies 收到这个,[Object: null prototype] {}

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

【问题讨论】:

  • theverge.com/2020/3/24/21192830/… 也许你可以尝试在 Safari 中启用“跨站跟踪”,看看问题是否与它有关。
  • 这确实有效。 Safari 和 Chrome 都登录并为下一次 api 调用保留了它们的令牌。不过,我不能指望用户更改该设置,那么我该从哪里修复呢?终于有东西了,谢谢。

标签: node.js express cookies netlify


【解决方案1】:

From MDN

浏览器正在迁移以将 cookie 默认设置为 SameSite=Lax。如果需要跨域发送 cookie,请使用 None 指令选择退出 SameSite 限制。 None 指令要求也使用 Secure 属性。

您在 Chrome 上做得正确(通过设置 sameSite=Nonesecure=true

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-02
    • 2017-09-11
    • 2017-04-17
    • 2011-08-13
    • 2019-06-17
    • 2017-11-24
    • 2017-07-13
    • 2020-05-17
    相关资源
    最近更新 更多