Cross-Origin Resource Sharing (CORS)

Christopher Makarem
2 min readNov 8, 2018

In order to keep a website and its users secure from the security risks involved with sharing resources across multiple domains the use of CORS is recommended, but what is CORS?

CORS, also known as Cross-Origin Resource Sharing, allows resources such as JavaScript and web fonts to be loaded from domains other than the origin parent domain.These days, a web page commonly loads images, stylesheets, scripts, etc. from other domains. Although, a few years ago due to security reasons, web fonts and AJAX (XML HTTP Requests) were normally restricted to the same-origin policy which restricted their use between domains. Now however, with the use of CORS, the browser and server can communicate to determine whether it is safe to allow a cross-origin request.

CORS Workflow

HTTP Request Headers
When a domain is requesting to interact with a resource on another domain, request headers are added from the first domain in order to use the cross-origin resource sharing feature. These are the HTTP request headers that may be associated with the requesting domain.

  • Origin
  • Access-Control-Request-Method
  • Access-Control-Request-Headers

HTTP Response Headers
The domain who’s resources are being requested can respond to the first domain with the following HTTP response headers based on what configuration options are set.

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Credentials
  • Access-Control-Expose-Headers
  • Access-Control-Max-Age
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

CORS Preflight
When more complicated, types of requests are performed, the browser will insert additional preflight requests to validate whether they have the appropriate permissions to perform the action. A request is preflighted if any of the following conditions are met (NOTE: preflight in this case means it is sent to the server before the actual request is attempted):

  • It uses an HTTP method other than GET or POST
  • Custom headers are set
  • The request body has a MIME type other than text/plain

Here is an example of a preflight request:

Origin: http://server1.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Here is an example respose to the preflight requst:

Access-Control-Allow-Origin: http://server1.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

--

--