Wednesday, 5 February 2014

Same-origin policy (SOP)

Same Origin Policy (SOP) is a web browser security measure that prevents JavasScript running in one site from accessing other sites (unless they're from the same origin). For example, if you have "random_site.com" open in one browser window and "gmail.com" in another, then you don't want a script from "random_site.com" to access your Gmail. Two pages are considered from the same origin if the protocol, port (if any) and host are the same.

Cross-origin resource sharing (CORS)

Cross-origin resource sharing (CORS) is a mechanism that allows scripts to bypass the Same-Origin Policy, essentially allowing JavasScript code to make requests to external sites. Such "cross-domain" requests would otherwise be forbidden by web browsers. When browsers issue requests, they always include the "Origin" header, the server can then pick up this "Origin" header and respond with an "Access-Control-Allow-Origin" header if that Origin is acceptable.  Browsers will then allow the access to go ahead.

CORS in Java

In your Java webapp, all you need to do is set the "Access-Control-Allow-Origin" CORS header to the Servlet response:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

As of Tomcat 7, CORS  support has been added (in the form of a filter). In theory, you can add this Tomcat-specific Servlet to the web.xml and it should take care of adding CORS headers (although that didn't really work for me): 

<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>

More info at:

CORS in Scala

If using Spray with Scala, for example, adding CORS headers to the response can be achieved using the following code: 

import spray.http._

path("your_path") {
 get{
  respondWithHeader(HttpHeaders.`Access-Control-Allow-Origin`(AllOrigins)){
    _.complete("server response")        
  }
 }
}