问题描述
如果我从Netlify进行api调用,我似乎无法设置cookie,但是使用Postman可以正常工作。
I can't seem to set the cookies if I make the api call from Netlify, but with Postman it works.
我不明白为什么。
我的代码如下:
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而失败
Then the code tries a different route right after which fails due to missing cookies
router.get('/user', accessjwtAuth <-- this fails due to no cookies, async (req, res) => {})
Netlify默认带有SSL证书。来自前端的调用如下所示:
Netlify comes with SSL certificate by default. The call from the frontend looks like this:
const config = {
baseURL: `${API_URL}/api/auth/login`,
method: 'post',
withCredentials: true,
headers: {'Content-Type': 'application/json',},
data: values,
};
axios(config).then((res) => {});
最后,快递应用的配置如下:
Lastly, the express app is configured like this:
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获取此内容, [对象:空原型] {}
I keep getting this for my signedcookies, [Object: null prototype] {}
我注意到此问题发生在Safari而非Chrome上。
在Chrome中,请求都具有 accessToken
& refreshToken
。
我还注意到,如果我设置 sameSite:'lax'
,则只有 refreshToken
被保留。 / p>
I noticed that this issue happens on Safari and not Chrome.In Chrome, the req has both accessToken
& refreshToken
.I also noticed that if I set sameSite: 'lax'
then only the refreshToken
gets preserved.
推荐答案
您使用Chrome的操作正确(通过设置 sameSite = None
和 secure = true
)
You are doing the correctly with Chrome (by setting sameSite=None
and secure=true
)
对于,我认为我们必须手动启用跨站点跟踪首选项。我想您可以告诉您的用户这样做,或者尝试考虑另一种无需跨站点Cookie即可实现该功能的方法。
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.
这篇关于未设置安全Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!