【问题标题】:Does Rails 5.2 API mode swallow default security headers?Rails 5.2 API 模式会吞下默认的安全标头吗?
【发布时间】:2019-05-06 10:55:56
【问题描述】:

如果我在application.rb 中输出config.action_dispatch.default_headers,我会看到所有standard rails headers

{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-Download-Options"=>"noopen", "X-Permitted-Cross-Domain-Policies"=>"none", "Referrer-Policy"=>"strict-origin-when-cross-origin"}

但是,如果我随后向我的应用程序(使用 curl/browser/postman)发出请求,我将看不到上述任何内容。我只看到以下内容:

$  curl -v -XGET 'localhost:4000/myresource/581'
* TCP_NODELAY set
* Connected to localhost (::1) port 4000 (#0)
> GET /myresource/581 HTTP/1.1
> Host: localhost:4000
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< ETag: W/"292a7d87b10e292374e765dd0b56fee7"
< Cache-Control: max-age=0, private, must-revalidate
< X-Request-Id: 7ff75ff6-f598-4489-9439-a4c17c6a5480
< X-Runtime: 0.025049
< Transfer-Encoding: chunked
<

这一切都在本地运行,没有网络服务器/代理。在生产中,我缺少相同的标题。

Rails API 模式是否会删除它认为与 API 无关的标头?还是只能是我的应用程序中的其他代码在执行此操作?

【问题讨论】:

    标签: ruby-on-rails http-headers rails-api ruby-on-rails-5.2


    【解决方案1】:

    API 模式下的 Rails 5.x 不包含 ActionDispatch 默认标头。

    这是一个问题:https://github.com/rails/rails/issues/34940

    但现在已经修复,将在 6.0.0 版本中提供:https://github.com/rails/rails/pull/32484

    【讨论】:

      【解决方案2】:

      几个月前我遇到了同样的问题,正如@Matheus 提到的,他们在rails 6 中解决了这个问题,但如果你被rails 5.2 卡住,这是我的情况,这就是我解决问题的方法,希望这可以帮助! ?:

      before_action :put_headers
      
        def put_headers
          response.set_header('Referrer-Policy', 'strict-origin-when-cross-origin')
          response.set_header('X-Content-Type-Options', 'nosniff')
          response.set_header('X-Frame-Options', 'SAMEORIGIN')
          response.set_header('X-XSS-Protection', '1; mode=block')
          response.set_header('Content-Security-Policy', "default-src 'self' https:; " \
              "img-src 'self' https:;" \
              "media-src 'none'; " \
              "object-src 'none'; " \
              "script-src 'self'; " \
              "style-src 'self' ")
        end
      

      请注意,上面只是一个example of configuration,意味着您需要为所有标题(例如内容安全策略)添加自己的逻辑到上面的配置中,还请务必在应用程序控制器上设置该代码( this site may help with security configuration)。

      【讨论】:

        猜你喜欢
        • 2011-05-28
        • 2011-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多