CORS Video Tutorial


In this tutorial I propose to demystify the principle of CORS.

The problem

By default, browsers impose a security policy same-origin which limits how a resource loaded from one origin can interact with a resource loaded from another origin. If you've ever tried making queries Cross-origin in Ajax you must have paid for this policy and encountered the error:

Access to fetch at 'XXXXX' from origin 'YYYYY' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

CORS to the rescue

CORS, for Cross-origin resource sharing, allows, through HTTP headers, to allow a user access to resources located on a different origin than the current site.

To indicate that your server accepts requests Cross-origin from the origin http: //domaine-a.localhost you must add the head Access-Control-Allow-Origin to your answer (this header can contain the origin or a wildcard *).

Access-Control-Allow-Origin: http: //domain-a.localhost

Preliminary motions preflight

The previous header is sufficient in the case of simple queries but for more complex cases the browser will make a preliminary request to verify what is authorized by the server. This query will use the method OPTIONS and will use the same path as the original query. You will need to respond to this request with CORS header to specify that you accept the headers and methods that will be sent to you.

Access-Control-Allow-Origin: http: //domain-a.localhost
Access-Control-Allow-Headers: X-Requested-With, Content-Type
Access-Control-Allow-Methods: POST, GET
  • Access-Control-Allow-Headers allows to specify additional headers that are accepted in cross-origin
  • Access-Control-Allow-Methods allows to limit the methods that will be usable in the case of a request cross origin.

And cookies?

Cookies can not be sent between 2 domains that have a different root. However it is quite possible to send cookies from a domain a.domain.ltd to a domain b.domain.ltd. For this there are several prerequisites:

  • The cookie must be registered for the root domain: Set-Cookie: key = value; Domain = domain.ltd; Path = /; Expires = Wed, 21 Oct 2020 07:28:00 GMT; HttpOnly
  • We must then specify that we want to include cookie headers
fetch ('https://domain.ltd', {
  credentials: 'include'
})
  • Finally the server must respond to the query with a Access-Control-Allow-Origin who is not a joker * and must include a new one in mind: Access-Control-Allow-Credentials: true

What if I do not have a hand on the server?

If you do not have the hand on the server the only solution to get around the policy same-origin is to create a proxy to the origin you want to call that will return the CORS headers.

Some bookstores

Here are some libraries to help you easily set CORS headers on your application.