Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS for only selected route rails

I am on Rails5 and I want to allow CORS on one of my route. Here is how I can allow CORS for all my route, but is there a way to only whitelist for one endpoint?

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
like image 302
aks Avatar asked Apr 15 '17 14:04

aks


People also ask

How do I enable CORS in rails?

Using rack-cors You need to inform Rails which origin it should allow. To do that, you need to create a new initializer for your application. This configuration will only allow HTTP POST calls to /order endpoint and all HTTP methods to any other endpoint. You need to pay close attention to the origins parameter.

Is disabling CORS safe?

CORS misconfigurations can also give attackers access to internal sites behind the firewall using cross-communication types of attacks. Such attacks can succeed because developers disable CORS security for internal sites because they mistakenly believe these to be safe from external attacks.

How do you fix CORS missing Allow origin?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do I enable CORS access?

Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.


1 Answers

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.

like image 152
sideshowbarker Avatar answered Oct 19 '22 21:10

sideshowbarker