我在我的 Rails 应用程序中启用了内容安全策略。当我在开发环境中本地运行它时,rails 错误页面被破坏,因为内联 JavaScript 和 CSS 被浏览器的内容安全策略阻止。我在 Google Chrome 中从 turbo.es2017-esm.js 收到以下错误:
拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self' localhost:3000 'nonce-vJgPXpdJcQ60SidkuK6V/Q=='”。启用内联执行需要“不安全内联”关键字、哈希值(“sha256-N8P082RH9sZuH82Ho7454s+117pCE2iWh5PWBDp/T60=”)或随机数(“nonce-...”)。
当我在谷歌浏览器中检查页面时,我看到
script
元素具有空 nonce
属性:
<script type="text/javascript" data-template="error_page" nonce="">
这可能是 javascript 被阻止的原因,因为脚本标签没有正确的随机数。有办法解决这个问题吗?
config/initializers/content_security_policy.rb
Rails.application.configure do
# The policies are set in config/environments/[development/test/production].rb
# Generate random nonce that will be used in <script> and <style> elements
config.content_security_policy_nonce_generator = -> (request) { SecureRandom.base64(16) }
# Add the nonce to the Content-Security-Policy header
config.content_security_policy_nonce_directives = %w(script-src style-src)
end
config/environments/development.rb
config.content_security_policy do |policy|
policy.default_src :self
policy.img_src :self, 'data:'
policy.script_src :self
policy.style_src :self
policy.connect_src :self
end
导轨:7.0.4.2 涡轮导轨:1.3.3
Javascript:@hotwired/turbo-rails:7.2.5 @hotwired/turbo:7.2.5 @hotwired/stimulus:3.2.1
我在 turbo.es2017-esm.js 的另一行 (:348) 有同样的错误。解决方案是删除我从该特定表单的表单字段中忽略的样式属性,并将其移动到适当的 css 类中。
因为上面有涡轮导轨并没有显示问题的确切来源。禁用它有帮助,因此浏览器 CSP 错误指向正确的行而不是 turbo.es2017-esm.js.