跨域Cookie是指在主域名不同的网站之间共享Cookie数据。由于浏览器的同源策略(Same-Origin Policy)限制,默认情况下Cookie只能在设置它们的域名下访问。
Safari浏览器由于其严格的隐私保护策略(如智能防跟踪功能ITP),对跨域Cookie有更严格的限制:
Set-Cookie: key=value; SameSite=None; Secure
SameSite=None
: 允许跨站请求携带CookieSecure
: 必须与SameSite=None一起使用,要求HTTPS连接服务器需要设置正确的CORS头部:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Credentials: true
客户端请求需要设置:
fetch('https://api.example.com', {
credentials: 'include'
});
通过同域代理转发跨域请求:
客户端 -> 同域代理服务器 -> 目标API
通过window.postMessage在不同域之间传递数据。
原因: ITP限制第三方Cookie有效期(7天后删除)
解决方案:
可能原因:
解决方案:
Set-Cookie: session=abc123; SameSite=None; Secure; Path=/
解决方案: 确保:
Access-Control-Allow-Credentials: true
credentials: 'include'
Access-Control-Allow-Origin
不能为*
,必须指定具体域名服务器端(Node.js)设置跨域Cookie:
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://client-domain.com');
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
app.get('/set-cookie', (req, res) => {
res.cookie('cross-site-cookie', 'value', {
sameSite: 'none',
secure: true,
httpOnly: true
});
res.send('Cookie set');
});
app.listen(3000);
客户端获取跨域Cookie:
fetch('https://api-domain.com/set-cookie', {
credentials: 'include'
})
.then(response => response.text())
.then(data => console.log(data));
没有搜到相关的文章