Programing

CORS 정책을 통해 모든 것을 허용

lottogame 2020. 8. 28. 07:47
반응형

CORS 정책을 통해 모든 것을 허용


Cors를 비활성화하려면 어떻게해야합니까? 어떤 이유로 허용 된 오리진과 헤더를 와일드 카드로 지정했지만 내 ajax 요청은 여전히 ​​내 CORS 정책에서 오리진을 허용하지 않는다고 불평합니다 ....

내 애플리케이션 컨트롤러 :

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :current_user, :cors_preflight_check
  after_filter :cors_set_access_control_headers

# For all responses in this controller, return the CORS access control headers.

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  headers['Access-Control-Allow-Headers'] = '*'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  if request.method == :options
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Max-Age'] = '1728000'
    render :text => '', :content_type => 'text/plain'
  end
end
  private
  # get the user currently logged in
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  helper_method :current_user

end

경로 :

  match "*all" => "application#cors_preflight_check", :constraints => { :method => "OPTIONS" }
  match "/alert" => "alerts#create"
  match "/alerts" => "alerts#get"
  match "/login" => "sessions#create"
  match "/logout" => "sessions#destroy"
  match "/register" => "users#create"

편집하다---

나는 또한 시도했다 :

   config.middleware.use Rack::Cors do
      allow do
        origins '*'
        resource '*', 
            :headers => :any, 
            :methods => [:get, :post, :delete, :put, :options]
      end
    end

application.rb에서

-편집 2 ---

문제는 Chrome 확장 프로그램이 CORS를 지원하지 않을 수 있다는 것입니다. CORS를 우회하는 정보를 어떻게 가져올 수 있습니까? 비행 전 확인에 어떻게 응답해야합니까?


rails-api를 사용한 공용 API에 대한 동일한 요구 사항이 있습니다.

또한 before 필터에 헤더를 설정했습니다. 다음과 같이 보입니다.

headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'

Access-Control-Request-Method 헤더를 놓친 것 같습니다.


rack-cors 미들웨어를 살펴보십시오 . 구성 가능한 방식으로 CORS 헤더를 처리합니다.


Simply you can add rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0

1st Step: add gem to your Gemfile:

gem 'rack-cors', :require => 'rack/cors'

and then save and run bundle install

2nd Step: update your config/application.rb file by adding this:

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

for more details you can go to https://github.com/cyu/rack-cors Specailly if you don't use rails 5.


I had issues, especially with Chrome as well. What you did looks essentially like what I did in my application. The only difference is that I am responding with a correct hostnames in my Origin CORS headers and not a wildcard. It seems to me that Chrome is picky with this.

Switching between development and production is a pain, so I wrote this little function which helps me in development mode and also in production mode. All of the following things happen in my application_controller.rb unless otherwise noted, it might not be the best solution, but rack-cors didn't work for me either, I can't remember why.

def add_cors_headers
  origin = request.headers["Origin"]
  unless (not origin.nil?) and (origin == "http://localhost" or origin.starts_with? "http://localhost:")
    origin = "https://your.production-site.org"
  end
  headers['Access-Control-Allow-Origin'] = origin
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
  allow_headers = request.headers["Access-Control-Request-Headers"]
  if allow_headers.nil?
    #shouldn't happen, but better be safe
    allow_headers = 'Origin, Authorization, Accept, Content-Type'
  end
  headers['Access-Control-Allow-Headers'] = allow_headers
  headers['Access-Control-Allow-Credentials'] = 'true'
  headers['Access-Control-Max-Age'] = '1728000'
end

And then I have this little thing in my application_controller.rb because my site requires a login:

before_filter :add_cors_headers
before_filter {authenticate_user! unless request.method == "OPTIONS"}

In my routes.rb I also have this thing:

match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}

and this method looks like this:

def empty
  render :nothing => true
end

I have had a similar problem before where it turned out to be the web brower (chrome in my case) that was the issue.

If you are using chrome, try launching it so:

For Windows:

1) Create a shortcut to Chrome on your desktop. Right-click on the shortcut and choose Properties, then switch to “Shortcut” tab.

2) In the “Target” field, append the following: –args –disable-web-security

For Mac, Open a terminal window and run this from command-line: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security

Above info from:

http://documentumcookbook.wordpress.com/2012/03/13/disable-cross-domain-javascript-security-in-chrome-for-development/


Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.

I am running Nginx and it was simple enough to just modify the my_app.conf file (where my_app is your app name). You can find this file in /etc/nginx/conf.d

If you do not have location / {} already you can just add it under server {}, then add add_header 'Access-Control-Allow-Origin' '*'; under location / {}.

The final format should look something like this:

server {
    server_name ...;
    listen ...;
    root ...;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
    }
}

Try configuration at /config/application.rb:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
  end
end

참고URL : https://stackoverflow.com/questions/17858178/allow-anything-through-cors-policy

반응형