乐闻世界logo
搜索文章和话题

How to use Cookies in cross-domain scenarios? What issues need attention?

3月6日 23:36

Using Cookies in cross-domain scenarios requires special attention because the browser's same-origin policy restricts Cookie access and transmission.

Same-origin policy and Cookies

  • Cookies are only sent in same-origin requests by default
  • Same origin: same protocol, domain, and port

Setting cross-domain Cookies

  1. Through Domain attribute
javascript
// Set Cookie on parent domain, accessible by subdomains document.cookie = "token=xyz; Domain=.example.com; Path=/";
  • Setting Domain to .example.com allows all subdomains to access
  • Note: Domain must be the parent domain or the same domain as the current domain
  1. Carrying Cookies in cross-domain requests
javascript
// Frontend setting fetch('https://api.example.com/data', { credentials: 'include' // or 'same-origin' }); // Or using XMLHttpRequest const xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.open('GET', 'https://api.example.com/data'); xhr.send();

Server-side configuration

javascript
// Express.js example app.use(cors({ origin: 'https://frontend.example.com', credentials: true // Allow carrying Cookies })); // Specify SameSite when setting Cookie res.setHeader('Set-Cookie', [ 'token=xyz; HttpOnly; Secure; SameSite=None' ]);

Relationship between CORS and Cookies

  • Must set credentials: 'include'
  • Server must set Access-Control-Allow-Credentials: true
  • Access-Control-Allow-Origin cannot be *, must be a specific domain

Third-party Cookie restrictions

  • Chrome, Firefox and other browsers are gradually restricting third-party Cookies
  • Safari has blocked third-party Cookies by default
  • Solution: Use SameSite=None; Secure

Use cases

  • Single Sign-On (SSO)
  • Cross-domain API authentication
  • Third-party login (OAuth)

Security considerations

  • Cross-domain Cookies must use the Secure flag
  • Verify Origin and Referer headers
  • Use CSRF Token for additional protection
  • Set reasonable expiration times
标签:Cookie