mike927
mike927

Reputation: 774

Rails CORS - simple request: allowed methods option is ignored

I build API based on Rails 5. I use 'rack-cors' gem to control CORS. Below code snipped I wonder about:

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', headers: :any, methods: %i()
      end
    end

I removed all HTTP methods from allowed methods array however still I can call GET, POST successfully (DELETE is forbidden and I get it). As I can see OPTIONS, GET, POST are ignored because even it's empty I can call server with these methods. Is it normal? If it is so how to forbid e.g. POST using CORS?

Upvotes: 1

Views: 1047

Answers (3)

Shahzad Tariq
Shahzad Tariq

Reputation: 2857

Rack-cors gem set default value of methods and headers to :get

So if you pass empty string or empty array or nil, it would take it as :any so it is allowing get, post etc requests.

Upvotes: 0

sideshowbarker
sideshowbarker

Reputation: 88408

That methods value only controls what method names the server sends back in the value of the Access-Control-Allow-Methods header in response to a CORS preflight OPTIONS request — that is, only for non-“simple” requests.

So if your request has characteristics that trigger a preflight, only then will browsers check the value of the Access-Control-Allow-Methods response header to see if the request method is allowed, and so only then will the methods value you’ve configured have any effect.

Otherwise, your browser will allow any cross-origin GET and POST that doesn’t trigger a preflight — any “simple” request — without regard to whatever methods value you’ve configured.

how to forbid e.g. POST using CORS?

You can’t forbid “simple” POST requests using CORS. You can only forbid non-simple POST requests — those that have for whatever reason triggered a preflight.

Or, by using the headers option, you can set the Access-Control-Allow-Headers header value — which will cause the browser to disallow any non-simple preflighted requests that have request headers with names other than the header names you’ve specified with that headers option.

Upvotes: 3

McMutton
McMutton

Reputation: 935

If you want to allow only specific methods, say GET and OPTIONS, try this:

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

More info here.

Upvotes: 1

Related Questions