浏览器阻止CORS cookie



我在一个自定义域api.example.com上使用Firebase函数。

当用户登录我的网站时,向服务器发送请求

await fetch(`https://api.example.com/test`, {
method: 'POST',
credentials: 'include',
})
.then(async function (response) {
if (response.status == 200) {
let text = await response.text();
console.log(text);
}
else {
console.log("Failed");
return null;
}
});

在Cloud Functions中触发测试端点,看起来如下:

exports.test = functions
.https.onRequest((request, response) => {
const expiresIn = 60 * 60 * 24 * 5 * 1000;
const origin = request.headers.origin;
const options = { maxAge: expiresIn, httpOnly: true, secure: true, sameSite: 'None'};
response.cookie('__session', "123456", options);
response.set('Access-Control-Allow-Origin', origin);
response.set('Access-Control-Allow-Credentials', true);
response.set('Access-Control-Allow-Headers', 'credentials');
response.end(JSON.stringify({ status: 'success' }));
})

问题是:mozilla, chrome, safari的浏览器开发工具显示服务器的响应,其中标头包含set-cookie: __session=123456; Max-Age=432000; Path=/; Expires=Mon, 30 Aug 2021 11:25:25 GMT; HttpOnly; Secure; SameSite=None,但cookie不存储在mozilla Firefox和safari中。在Chrome中,它被存储,但在页面刷新后被删除,尽管它应该持续存在。

我在这里做错了什么?有什么建议吗?

我找到了解决方案。我还没有为cookie选项指定一个域。

应该像下面这样:

exports.test = functions
.https.onRequest((request, response) => {
const expiresIn = 60 * 60 * 24 * 5 * 1000;
const origin = request.headers.origin;
const options = { maxAge: expiresIn, httpOnly: true, secure: true, sameSite: 'None', domain: 'example.com'};
response.cookie('__session', "123456", options);
response.set('Access-Control-Allow-Origin', origin);
response.set('Access-Control-Allow-Credentials', true);
response.set('Access-Control-Allow-Headers', 'credentials');
response.end(JSON.stringify({ status: 'success' }));
})

相关内容

  • 没有找到相关文章

最新更新