【问题标题】:Allow anything through CORS Policy通过 CORS 政策允许任何事情
【发布时间】:2013-07-25 08:31:56
【问题描述】:

如何禁用 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 获取信息?我应该如何应对预检检查?

【问题讨论】:

  • 不是“禁用 CORS”但实际上没有策略?我似乎无法回应任何请求。
  • 你在 localhost 上使用这个吗?

标签: ruby-on-rails cors


【解决方案1】:

我对使用 rails-api 的公共 API 有相同的要求。

我还在前置过滤器中设置了标题。它看起来像这样:

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 标头。

【讨论】:

【解决方案2】:

看看rack-cors 中间件。它将以可配置的方式处理 CORS 标头。

【讨论】:

  • 我们已经使用 rack-cors 几个月了,到目前为止没有遇到任何问题。你确定问题不在客户端吗?
  • 我认为问题在于 Chrome 扩展不支持 CORS,所以可能 Origin 为 Null。如何完全禁用 CORS 并响应任何请求,包括具有 Null 来源的请求?
  • 你在用什么 Chrome 扩展?
  • 我正在编写一个需要与我的 Rails 后端通信的 chrome 扩展。
【解决方案3】:

只需添加 rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0

第一步: 将 gem 添加到您的 Gemfile:

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

然后保存并运行bundle install

第二步: 通过添加以下内容更新您的 config/application.rb 文件:

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

更多详情可以去https://github.com/cyu/rack-cors 特别是如果你不使用 rails 5。

【讨论】:

  • 对我来说.insert_before 0 很重要。在我使用 config.middleware.use 之前,它只在我想为我的 public 目录允许 CORS 之前有效。
【解决方案4】:

我遇到了问题,尤其是 Chrome。你所做的看起来基本上就像我在我的应用程序中所做的一样。唯一的区别是我在我的 Origin CORS 标头中使用正确的主机名进行响应,而不是通配符。在我看来,Chrome 对此很挑剔。

在开发和生产之间切换很痛苦,所以我写了这个小函数,它可以帮助我在开发模式和生产模式下使用。以下所有事情都发生在我的application_controller.rb 中,除非另有说明,这可能不是最好的解决方案,但rack-cors 也对我不起作用,我不记得为什么了。

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

然后我的application_controller.rb 中有这个小东西,因为我的网站需要登录:

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

在我的routes.rb我也有这个东西:

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

这个方法看起来像这样:

def empty
  render :nothing => true
end

【讨论】:

  • 只是为了关闭这个圈子。只有当您从 localhost 应用程序访问生产后端时,才会发生整个 CORS 混乱,对吗?当一切都投入生产时,这一切都不会发生?
  • 仅当后端和 webapp 托管在同一个 URL 下时。如果它们完全托管在两个不同的 URL 下,那么这也会发生在生产环境中。
【解决方案5】:

我之前遇到过类似的问题,原来是网络浏览器(在我的情况下是 chrome)是问题所在。

如果您使用的是 chrome,请尝试这样启动它:

对于 Windows:

1) 在桌面上创建 Chrome 的快捷方式。右键单击快捷方式并选择“属性”,然后切换到“快捷方式”选项卡。

2) 在“目标”字段中,附加以下内容:–args –disable-web-security

对于 Mac,打开终端窗口并从命令行运行: 打开 ~/Applications/Google\ Chrome.app/ –args –disable-web-security

以上信息来自:

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

【讨论】:

  • 为什么这被否决了?我遇到的情况类似于问题中描述的情况,该问题通过在禁用网络安全的情况下运行 chrome 得到解决。当您在本地运行开发服务器时会出现此问题。显然,您不会让 chrome 在始终禁用网络安全的情况下运行。
  • 这不应该被否决,因为他正确地解释了情况:)
  • 我没有投反对票,但从答案来看,尚不清楚这只是出于开发目的的解决方案。虽然这可能会在本地解决问题,但不能指望您的网络访问者/扩展程序用户这样做。所以我会在答案中澄清这一点。
  • 这里也没有投票,但曾经是 chrome 的第一个实例使用给定标志运行会导致所有其他实例以相同的方式运行。需要非常提防的事情。很容易忘记并做一些即兴冲浪。
【解决方案6】:

刚刚在生产中的 Rails 应用程序中遇到了这个问题。这里的很多答案给了我提示,并帮助我最终得出了一个适合我的答案。

我正在运行 Nginx,只需修改 my_app.conf 文件(其中 my_app 是您的应用程序名称)就足够简单了。你可以在/etc/nginx/conf.d找到这个文件

如果您还没有location / {},您可以将其添加到server {} 下,然后在location / {} 下添加add_header 'Access-Control-Allow-Origin' '*';

最终的格式应该是这样的:

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

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

【讨论】:

  • OPTIONS 请求怎么样?
【解决方案7】:

在 /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

【讨论】:

  • 你忘了说开发者应该在 Gemfile 中添加 'rack-cors'
【解决方案8】:

使用 VSC 或任何其他具有 Live 服务器的编辑器,它会给你一个代理,允许你使用 GET 或 FETCH

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 2023-03-30
    • 2019-09-16
    • 1970-01-01
    • 2021-11-07
    • 2020-11-02
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多