CORS
CORS (Cross Origin Resource Sharing) is the mechanism which controls access to web resources outside
of the requester’s domain. CORS access is negotiated through a preflight OPTIONS
requests. An example
request might look like:
OPTIONS /cors/example/resource/ HTTP/1.1
... Some irrelevant headers
Origin: http://trusty.mctrusterson
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Configure, Content-Type
Origin
refers to the domain this request originates, in the example trusty.mctrusterson.
Access-Control-Request-Method
is an additional security feature which the server can use to restrict
access of a resource to certain methods. Regardless of whether this feature is implemented or not, the
only methods allowed for a cross origin request are POST, GET, and HEAD.
Access-Control-Request-Headers
is a comma delimited list of headers the actual (not this pre-flight)
request would like to use.
After inspecting the pre-flight request the server must decide whether a request from that Origin
using the HTTP method in Access-Control-Request-Method
with the headers in
Access-Control-Requeset-Headers
would be allowed, if so it returns a 200
response otherwise it
should return a 401
. An example:
HTTP/1.1 200 OK
... some irrelevent headers
Access-Control-Allow-Origin: *
Access-Control-Request-Method: POST, GET, HEAD
Access-Contorl-Allow-Headers: X-Configure, Content-Type,
Access-Control-Allow-Origin
specifies to the client what origins are allowed access to this
resource. *
is used as a wild card, allowing any domain access.
Access-Control-Request-Method
contain a list of allowed http methods for this resource.
Access-Control-Allow-Headers
contain a list of allowed headers
Access-Control-Allow-Origin
is the only header required every time. All the other response
headers are only required if the server implements a related restriction.
There are a few more options available, for an in-depth article on everything CORS visit https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS or visit the spec https://www.w3.org/TR/cors/#access-control-allow-origin-response-header