Notes on CORS

Notes on CORS

The CORS standard describes HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission. It is generally the browser's responsibility to support these headers and honor the restrictions they impose.

The following diagram shows how CORS works:

These are request-response scenarios of how CORS works; the browser sends the OPTIONS request with an "Origin" HTTP header. The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:

Origin: http://www.example.com

The server at service.example.com may respond with:

  • An Access-Control-Allow-Origin header in its response indicating which origin sites are allowed. For example:

Access-Control-Allow-Origin: http://www.example.com

  • An error page if the server does not allow the cross-origin request
  • An Access-Control-Allow-Origin header with a wildcard that allows all domains:

Access-Control-Allow-Origin: *

A wildcard same-origin policy is appropriate when a page or API response is considered completely public content and it is intended to be accessible to everyone, including any code on any site. For example, a freely-available web font on a public hosting service like Google Fonts. 

The following diagram shows how CORS can be exploited, if the "Access-Control-Allow-Origin" header is allowed for any "Origin" request header it receives:

The mitigation:

Use a whitelist of trusted domains; one way to perform this is to have the server read the Origin header from the client, compare that to the list of domains that are allowed, and if it matches, echo the value of the Origin header back to the client as the Access-Control-Allow-Origin header in the response. For example, by adding the following code to .htaccess:

SetEnvIf Origin "^http(s)?://(.+\.)?(domain\.org|domain2\.com)$" origin_is=$0 

Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is

Main reff:

  • https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
  • https://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains


To view or add a comment, sign in

More articles by Aldo E. Majiah

Others also viewed

Explore content categories