Ruby on Rails - Rack-Cors Multiple Origins with Different Resources

ruby on rails - rack-cors multiple origins with different resources

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

Rails 5.1 CORS - how to set different origins for different environments

There are a few different options. One is to use secrets.yml file. There you can define different values per environment, let's say:

development:
allowed_origins:
- http://localhost:4200

production:
allowed_origins:
- http://productionurl1.com
- http://productionurl2.com

Then in your configuration file you can do

module Api
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins Rails.application.secrets.allowed_origins
end
end
end

Another option (taken from the comments) is to use the environment files, eg:

development.rb

config.allowed_cors_origins = ["http://localhost:4200"]

Then in the cors.rb initializer you can do:

Rails.application.config.allowed_cors_origins 

(since initializer will be called after the environment config file, this should work).

How to test if Rails rack-cors gem is working

To test CORS locally, I found this repo: https://github.com/njgibbon/nicks-cors-test

Just clone it, and click on the html file so it opens in your browser. By default it is calling the github API (https://api.github.com) and fetching info from there. You can open the console and check it.
If you change it to https://google.com it will throw a CORS restriction.

Similarly, you can change it to http://localhost:3000/api/v1/users (in my case) and it will throw a CORS error with the config I have now.

To double-check, just go to cors.rb and put origins "*". Restart the app server and try running again the html file. Now we won't be blocked.

How to enable CORS for only selected route rails

To allow cross-origin requests for only a certain endpoint path, use it as the first resource arg:

config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/endpoint/to/allow', :headers => :any, :methods => [:get, :post, :options]
end
end

That’ll allow cross-origin requests only for the path /endpoint/to/allow.

If you want to allow multiple paths, you can specify multiple resource declarations:

config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/endpoint/to/allow', :headers => :any, :methods => [:get, :post, :options]
resource '/another/endpoint/', :headers => :any, :methods => [:get, :post, :options]
end
end

https://github.com/cyu/rack-cors#resource has more details.



Related Topics



Leave a reply



Submit