Dave Lyon

Blog

View My GitHub Profile

Cross Origin Resource Sharing on Rails

While working on creating a bookmarklet for my new link sharing site, I ran in to a new solution to a common cross site scripting issue that allows POST requests to be sent from different originating sites.

Cross-Origin Resource Sharing (CORS) is a new mechanism for allowing sites to allow cross site scripting access with certain restrictions. A draft specification is available here: http://www.w3.org/TR/cors/. Essentially, CORS is a conversation you can choose to have with supporting browsers (IE8 and 9, Safari, and Chrome at this time) that will notify the browser that it should either allow or deny a specific request to a different originating server.

There are two ways this is handled:

  • Simple Requests - Must be a GET or POST request, and must send a Content-Type to the server of application/x-www-form-urlencoded, multipart/form-data, or text/plain. Must also NOT set any custom headers in the request. No verification needed other than an 'Access-Control-Allow-Origin' header with either '*' or the domain the request was sent from as the value
  • Complex Requests - Any other request will send an HTTP 'OPTIONS' request first in order to 'pre-flight' check the request the browser would really like to send. A good example of how this request looks is available here: https://developer.mozilla.org/en/HTTP_access_control
  • So what does it take to get this working in Rails 3? Surprisingly, not all that much! The quick and dirty solution is as follows:

    However, I would very much like to add broader support for the spec I linked to above, and plan on turning this in to some sort of plugin soon.