Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set allowed origin to request host in Rails 5

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?

like image 398
Severin Avatar asked Jan 28 '26 19:01

Severin


2 Answers

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
like image 66
Daniel Westendorf Avatar answered Jan 30 '26 15:01

Daniel Westendorf


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
like image 32
D1ceWard Avatar answered Jan 30 '26 15:01

D1ceWard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!