I am writing an application with a couple of APIs that should be accessible from any host. Now, so far I have handled this in my application.rb in the following way:
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*'
}
However, one of the clients that accesses the API doesn't allow to get data from sources where '*' is defined. My idea was to set the allowed origin dynamically to the one that requests the API. Something like this:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins ActionDispatch::Request.headers['Host']
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
But since cors.rb is an initializer, it doesn't have access to the requests that come in. Is there a way to make the origins list dynamic, so it will always just include the request host?
You could simply do this with a before_action within your controller.
class ApiBaseController < ApplicationController
before_action :set_cors_headers
private
def set_cors_headers
response.set_header "Access-Control-Allow-Origin", origin
end
def origin
request.headers["Origin"] || "*"
end
end
And if you do this ?
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
# this proc should return true or false
origins { |source, env| true }
resource '*', headers: :any, methods: %i[get post put patch delete options head]
end
end
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