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

How to set Cookies with CORS requests

1个答案

1

When implementing Cross-Origin Resource Sharing (CORS), setting and sending cookies is a critical step due to security and privacy concerns. To successfully set cookies in CORS requests, both client-side and server-side configurations are necessary.

Client-Side Configuration

On the client side, when sending a CORS request, such as using the fetch API, you must specify the credentials option in the request. This option instructs the browser on how to handle cookies in cross-origin requests. It has three possible values:

  • omit: Default. Cookies are not sent with the request, and third-party cookies are excluded from the response.
  • same-origin: Cookies are sent only when the URL is same-origin.
  • include: Cookies are sent regardless of whether the request is cross-origin.

For example, to include cookies in cross-origin requests, set credentials to include:

javascript
fetch("https://example.com/data", { method: "GET", credentials: 'include' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

Server-Side Configuration

On the server side, you must set response headers to allow specific cross-origin requests to carry cookies. This is primarily achieved by setting the Access-Control-Allow-Credentials header to true and explicitly specifying Access-Control-Allow-Origin (without using the wildcard *):

http
Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: https://yourwebsite.com

Additionally, when setting cookies, you may need to configure the SameSite attribute. In cross-site requests, setting SameSite to None allows cookies to be sent, but you must also set the Secure attribute to ensure cookies are transmitted exclusively over secure HTTPS connections.

http
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; SameSite=None; Secure

Practical Example

Suppose you are developing an application across multiple domains, such as an API on example.com accessed by example-client.com to handle cookies. The server must appropriately set CORS headers to accept requests from example-client.com and manage cookies. The client must explicitly indicate a desire to include credentials (e.g., cookies) when making requests.

This is the basic process and configuration for setting and sending cookies in CORS requests. Such configurations ensure your application can securely handle user data across domains.

2024年8月12日 14:14 回复

你的答案