未设置安全cookie

Jos*_* K. 3 cookies node.js express netlify

如果我从 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 );
});
Run Code Online (Sandbox Code Playgroud)

然后代码立即尝试不同的路线,但由于缺少 cookie 而失败

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

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) => {});
Run Code Online (Sandbox Code Playgroud)

最后,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();
});
Run Code Online (Sandbox Code Playgroud)

我不断收到这个作为我的签名cookies,[Object: null prototype] {}

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

don*_*han 5

来自MDN

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

You are doing the correctly with Chrome (by setting sameSite=None and secure=true)

For the Safari with its major update to Safari Intelligent Tracking Prevention (ITP), I think we have to manually enable the Cross-site tracking preference. I think you could tell your users to do it or try to think of another way to implement the feature without cross-site cookie.