Wednesday, June 17, 2015

CORS : Cross-Origin Resource Sharing

The future of the web is cross-domain, not same-origin. As CORS continues the spirit of the open web by bringing API access to all.


The same-origin policy is an important security concept implemented by web browsers to prevent Javascript code from making requests against a different origin (e.g., different domain) than the one from which it was served.


Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed. CORS is a technique for relaxing the same-origin policy, allowing Javascript on a web page to consume a REST API served from a different origin.

Simple implementation:


In the simplest scenario, cross-origin communications starts with a client making a GET, POST, or HEAD request against a resource on the server. In this scenario, the content type of a POST request is limited to application/x-www-form-urlencoded, multipart/form-data, or text/plain. The request includes an Origin header that indicates the origin of the client code.


The server will consider the request's Origin and either allow or disallow the request. If the server allows the request, then it will respond with the requested resource and an Access-Control-Allow-Origin header in the response. This header will indicate to the client which client origins will be allowed to access the resource. Assuming that the Access-Control-Allow-Origin header matches the request's Origin, the browser will allow the request.

On the other hand, if Access-Control-Allow-Origin is missing in the response or if it doesn't match the request's Origin, the browser will disallow the request.

For simple CORS requests, the server only needs to add the following header to its response:

Access-Control-Allow-Origin: *

It differs to implement CORS for specific platforms. Suppose for tomcat a minimal CORS configuration as:


<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>




N.B: Bear in mind that CORS is not about providing server-side security. The Origin request header is produced by the browser and the server has no direct means to verify it.



No comments: