Blog

Cross-Origin Resource Sharing

Team Avatar - Mikel Lindsaar
Mikel Lindsaar
July 12, 2014

One of the fun things about web application development, is no matter how long you have been in the game, things are always changing and there are new challenges to resolve.

For example, today, while working on an application, we were getting custom font rendering issues. I knew this was a Cross-Origin Resource Sharing problem, as I had seen it before, but I had totally forgotten how to fix it :)

I clued onto this because Chrome was reporting:

Redirect at origin ‘https://123456789.cloudfront.net’ has been blocked from loading by Cross-Origin Resource Sharing policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://website.com’ is therefore not allowed access”

The application in question uses AWS Cloudfront as it’s CDN. Cloudfront is set to have the application as the origin, which means we don’t need to use gems like asset-sync to keep an S3 bucket in harmony with our deployed application. However, when googling for the problem, I couldn’t find a solution that didn’t involve S3. So that meant I needed to go hunt.

Happily, the solution was quite simple. Use the rack-cors gem (source code).

Because we aren’t using S3 for our assets, we just need to make sure that two things happen and then test with a third:

1) Our Rails app says it’s ok for the browser to fetch assets from Cloudfront

Install the rack-cors gem in your Gemfile:

group :production, :staging do gem 'rack-cors', :require => 'rack/cors' end

Then edit your environment file to add in the details for the CORS headers:

``` # Enable serving of images, stylesheets, and JavaScripts from an asset server. config.action_controller.asset_host = “https://123456789.cloudfront.net”

config.middleware.insert_before 0, “Rack::Cors” do allow do origins “https://123456789.cloudfront.net” resource ‘*’, :headers => :any, :methods => [:get, :options] end end ```

The origins directive is passed a string that needs to match your CDN (domain name changed to protect the innocent)

2) That cloudfront passes through these headers when it is serving files.

This also is not too bad. Go into your cloudfront settings in the AWS console, select your distribution, then go into “Distribution Settings”.

Then choose Behaviours and edit the behaviour that services your Rails app (in my case it is the Default (*) behaviour)

Then in the “Forward Headers” select box, change it to “Whitelist” and choose “Origin” and add it to the list.

3) Test

With the above done, save your settings and let the Cloudfront system redeploy (this can take a while) and you should be good to go.