未设置安全 cookie

Secure cookies not being set

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

我一直在为我的 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),我认为我们必须手动启用 Cross-site 跟踪首选项。我认为您可以告诉您的用户这样做,或者尝试想出另一种方法来实现该功能而无需 cross-site cookie。