8

I'm implementing CORS in my rails application using rack-cors gem for it, but I'm not sure how can i define different resources for different origins.

I need something like that:

config.middleware.insert_before 0, Rack::Cors do

  allow do
    origins 'http://localhost:3000'
    resource '/api/*', headers: :any, methods: [:get, :post, :options, :put, :delete]
  end

  allow do
    origins 'http://localhost:6000'
    resource '*', headers: :any, methods: [:get, :post, :options, :put, :delete]
  end

end

So it will allow "http://localhost:3000" to access only '/api/*' and allow 'http://localhost:6000' to access all. is it possible?

is the above code the correct code/syntax for doing that?

thanks.

charlysisto
  • 3,710
  • 15
  • 27
yl2015
  • 311
  • 1
  • 3
  • 17

2 Answers2

14

I know this is a little old but for those finding this I am solving this differently with Rails 5.1.4 api only

-

Origins

ENV['CORS_ORIGINS'] = 'https://domain.first.com, http://another.origin.io'

Cors

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ENV['CORS_ORIGINS'].split(',').map { |origin| origin.strip }

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end
ALFmachine
  • 387
  • 4
  • 11
  • I don't get your answer, as the question was how to restrict different domains to access to different resources. I'm not sure your example does the job for this part > So it will allow "http://localhost:3000" to access only '/api/*' – zauzaj Mar 30 '19 at 15:40
  • Seems like `origins` doesn't like array in my case. This approach doesn't work for me – Rahul Dess Jun 13 '19 at 21:01
5

After checking and testing it turns out it is the right syntax. You can add as many blocks as you need:

allow do
    origins '[the domain]'
    resource '[the resource/directories]', headers: :any, methods: [:get, :post, :options, :put, :delete]
end
yl2015
  • 311
  • 1
  • 3
  • 17