未设置安全Cookie

问题描述

如果我从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,maxAge: 7 * 24 * 60 * 60 * 1000,// <-- I also tried lax
   }).send( // something );
});

然后代码立即尝试其他路由,此后由于缺少cookie而失败

router.get('/user',accessjwtAuth <-- this fails due to no cookies,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();
});

我一直在使用我的签名Cookie [Object: null prototype] {}

我注意到此问题发生在Safari而非Chrome上。 在Chrome中,要求同时具有accesstokenrefreshToken。 我还注意到,如果我设置sameSite: 'lax',那么只有refreshToken被保留。

解决方法

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即可实现该功能的方法。