【问题标题】:Rails 5.1 CORS - how to set different origins for different environmentsRails 5.1 CORS - 如何为不同的环境设置不同的来源
【发布时间】:2018-10-03 18:26:22
【问题描述】:

我正在使用带有 Rail 5.1 API 的 rack-cors gem。

根据文档,我有以下初始化程序:

config/initializers/cors.rb

module Api
  Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins ['http://localhost:4200','https://app.mydomain.com/']

      resource '*',
        headers: :any,
        :expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],        
        methods: [:get, :post, :put, :patch, :delete, :options, :head]
    end
  end
end

但是,这意味着当部署到生产环境时,我的 api 将接受来自任何 localhost:4200 来源的请求。

如何将这些设置分开,以便不同的环境可以有不同的允许来源?

【问题讨论】:

    标签: ruby-on-rails cors rack-cors


    【解决方案1】:

    有几个不同的选项。一种是使用secrets.yml 文件。在那里你可以为每个环境定义不同的值,比如说:

    development:
      allowed_origins:
        - http://localhost:4200
    
    production:
      allowed_origins:
        - http://productionurl1.com
        - http://productionurl2.com
    

    然后在你的配置文件中就可以了

    module Api
      Rails.application.config.middleware.insert_before 0, Rack::Cors do
        allow do
          origins Rails.application.secrets.allowed_origins
        end
      end
    end
    

    另一个选项(取自 cmets)是使用环境文件,例如:

    开发.rb

    config.allowed_cors_origins = ["http://localhost:4200"]
    

    然后在cors.rb初始化器中你可以这样做:

    Rails.application.config.allowed_cors_origins 
    

    (因为初始化程序将在环境配置文件之后调用,这应该可以工作)。

    【讨论】:

    • 谢谢,这是个好主意。您提到了其他选项 - 您将如何使用已经存在的环境文件?这肯定会更好,因为这些是与环境相关的设置?
    • 如果你想使用环境配置文件,你可以在development.rb文件中写config.allowed_cors_origins = ["http://localhost:4200"]之类的东西,然后在cors.rb初始化器中你可以做origins Rails.application.config.allowed_cors_origins - 因为初始化器将在环境配置文件之后调用,这应该可以工作。
    • 第二个选项对我有用。我在环境变量中使用了 figaro gem,它一直在抛出错误。在 production/development.rb 上设置允许的来源虽然效果很好
    【解决方案2】:

    对于使用 rails 5.2 的任何人,secrets.yml 已更改,现在我们需要使用凭据。为了使用它,我们需要编辑config/credentials.yml.enc 首先,运行命令EDITOR="atom --wait" rails credentials:edit(使用您选择的编辑器)。然后,按照accepted answer 的建议添加来源:

    development:
      allowed_origins:
       - http://localhost:4200
    
    production:
      allowed_origins:
       - http://productionurl1.com
       - http://productionurl2.com
    

    保存文件。现在允许的来源变量将在加密文件中。然后在 cors 初始化程序中(在我的情况下,它在 application.rb 中)

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins Rails.application.credentials[Rails.env.to_sym][:allowed_origins]
        resource '*',
        headers: :any,
        expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
        methods: [:get, :post, :options, :delete, :put]
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2021-07-09
      • 2018-10-24
      相关资源
      最近更新 更多