【问题标题】:Rails 5.2 CORS blockedRails 5.2 CORS 被阻止
【发布时间】:2019-09-02 18:18:36
【问题描述】:

提前感谢任何可以帮助我的人 !!

我正在运行一个带有 React 和 Webpacker 的 Rails 5.2 应用程序,我想在我的用户登录时显示一个 Gravatar 图标,但我一直被浏览器 CORB 阻止。

我已经阅读了所有 Rack CORS 文档和有关使用 CORS 设置导轨的 Stack Overflow 条目,但我似乎仍然无法让它工作。我的标题中没有看到allowed-origins,并且对 Gravatar.com 的请求继续被阻止。

我已经用我的主机名设置了我的config/credentials.yml.enc,如https://stackoverflow.com/a/56772510/759615 中所述:

development:
 allowed_origins:
   - http://localhost:3000
   - http://127.0.0.1:3000

production:
 allowed_origins:
   - http://productionurl1.com
   - http://productionurl2.com

application.rb:

  class Application < Rails::Application

    config.load_defaults 5.2

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins Rails.application.credentials[Rails.env.to_sym][:allowed_origins]

        resource '*',
                 headers: :origin,
                 methods: [:get, :post, :options, :put]
      end
    end
  end

我还在application.rb 中尝试了一个完全开放的 CORS 配置,只是为了测试这个概念:

...
     allow do
        origins '*'
    ...

对于本地环境,我在 config/webpacker.yml 中设置了 dev_server 的标头

      'Access-Control-Allow-Origin': 'http://localhost:3000/'

(我也尝试了 Webpacker 主机名127.0.0.1,但无济于事)

有很多变量,我可能遗漏了某些内容或更可能误解了文档中的含义,但我真的希望那里有人能提供我正在寻找的 CORS 答案!

【问题讨论】:

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


    【解决方案1】:

    我在我的项目中使用Rack::Cors 没有变量:

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'localhost:5000', /https*:\/\/.*?domain\.(com|org)\/*/, /https:\/\/another_domain\.my_domain\.org/
        resource '*', headers: :any, methods: :any, credentials: true
      end
    end
    

    而且效果很好。

    【讨论】:

    • @GLaDOS 你用过credentials: true吗?
    • @mechincov,是的,在您发表评论之后,我在回复之前尝试了您在 Rack::Cors 设置中的所有内容。
    【解决方案2】:

    如果所有连接都在中间件中打开(又名通配符原始连接设置为“*”),您可能会遇到安全错误:

    'initialize': Allowing credentials for wildcard origins is insecure. 
    Please specify more restrictive origins or set 'credentials' to false
    in your CORS configuration. (Rack::Cors::Resource::CorsMisconfigurationError)
    

    您可以使用正则表达式来设置正确的权限:

    use Rack::Cors do
    allow do
      # regular expressions can be used here
      origins 'localhost:3000', '127.0.0.1:3000', /\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/
    
      resource '/file/list_all/',
        headers: 'x-domain-token'
    
      resource '/file/at/*',
        methods: [:get, :post, :delete, :put, :patch, :options, :head],    
        headers: 'x-domain-token',
        # headers to expose  
        expose: ['Some-Custom-Response-Header'],
        max_age: 600
    end
    

    查看rack-cors 的文档并寻找其他示例。

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2019-08-03
      • 1970-01-01
      • 2020-09-11
      • 2021-04-16
      • 2015-10-09
      • 2018-10-18
      • 2018-12-23
      • 2018-02-26
      相关资源
      最近更新 更多