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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With