Can't render iframe on another domain using rack-cors

523 views Asked by At

I'm trying to render an iframe of App A within App B.

  • App A is a local Rails 5.0 app and is using https.
  • App B is hosted on Heroku and is using https.

I've tried implementing the rack-cors gem but with no success, and I've tried all the suggestions I can find on StackOverflow.

My cors.rb file, within App A:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'https://app-b.herokuapp.com'
    resource '/url/on/app_a/*',
             headers: :any,
             methods: :any
  end
end

My config.ru file (I've tried with and without this):

# This file is used by Rack-based servers to start the application.

require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
require 'rack/cors'

use Rack::Cors do
  allow do
    origins 'https://app-b.herokuapp.com'
    resource '/url/on/app_a/*',
             headers: :any,
             methods: :any
  end
end

The error I get is: Refused to display 'https://app-a.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

1

There are 1 answers

1
marcus.salinas On

I am not sure if this is specifically to rack-cors, but I do know that the header 'X-Frame-Options' is intentionally set to 'sameorigin' for at least Rails 5. Most likely to prevent developers from unintentionally allowing someone to wrap their server in an iframe.

According to the docs, we can see that if the server sets this response as not 'sameorigin', then the browser will allow the HTML code to run. So what we need is to remove that header away. Chris Peters does a great job at this post. To save a click

class SomeController < ApplicationController
  after_action :allow_iframe

  
  private

  def allow_iframe
    response.headers.except! 'X-Frame-Options'
  end
end

To apply this to all endpoints simply place the after_action line and the function code in the application controller, but I would suggest limiting this to only specific pages/controllers.