cyu / rack-cors

Rack Middleware for handling Cross-Origin Resource Sharing (CORS), which makes cross-origin AJAX possible.
MIT License
3.26k stars 263 forks source link

Wrong response headers are being sent #220

Closed straversi closed 3 years ago

straversi commented 3 years ago

Context

I have an API on which I allow all origins. However, I want to restrict one of the endpoints to only allow credentialed requests from one of my subdomains. My initializer configuration looks like this:

  allow do
    origins '*'
    resource '/api/v1/*',
             headers: :any,
             methods: %i[get post patch put]
  end

  allow do
    origins 'https://sub.domain.com'
    resource '/api/v1/resource/',
             headers: :any,
             methods: %i[get],
             credentials: true
  end

And my client fetch from sub.domain.com looks like this:

fetch('https://my.domain.com/api/v1/resource/', {credentials: 'include'})

The problem

I get the following client error: "Access to fetch at 'https://my.domain.io/api/v1/resource/' from origin 'https://sub.domain.com' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'."

I am explicitly only allowing 'https://sub.domain.com' for the resource '/api/v1/resource/'. Is there an obvious configuration issue here? I've confirmed in my client request that https://sub.domain.io is value of the Origin header.

mathewdbutton commented 3 years ago

@straversi I had a similar problem and a similar set of rules as you, and it seems that the rules are evaluated top down (from what I can tell). So it's matching on that wildcard rule first.

I think if you swap the order of your rules it should get through

  allow do
    origins 'https://sub.domain.com'
    resource '/api/v1/resource/',
             headers: :any,
             methods: %i[get],
             credentials: true
  end

  allow do
    origins '*'
    resource '/api/v1/*',
             headers: :any,
             methods: %i[get post patch put]
  end
straversi commented 3 years ago

Amazing, that was it. Thank you for that insight!