Turbolinks-拒绝执行内联脚本,因为它违反了以下内容安全政策

时间:2018-10-17 09:02:49

标签: ruby-on-rails ruby-on-rails-5 content-security-policy turbolinks

我正在使用“ Turbolinks 5.1.0”。


文件:Gemfile

gem'turbolinks','〜> 5.1'


文件:应用程序布局标题

<%= javascript_include_tag "application", nonce: true %>

文件:config / initializers / content_security_policy.rb

Rails.application.config.content_security_policy_nonce_generator =->请求{SecureRandom.base64(16)}


Google Chrome控制台错误

VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
  

[仅报告]拒绝执行内联脚本,因为它违反了   以下内容安全策略指令:“ script-src'self'https:   'unsafe-inline''nonce-UiVx2CiP0HHN9jOOSEG43g =='“。请注意   如果存在哈希或随机数值,则忽略“ unsafe-inline”   在源列表中。

n.assignNewBody @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
n.replaceBody @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
(anonymous) @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
t.renderView @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
n.render @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
t.render @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
e.renderSnapshot @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
e.render @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
t.render @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
(anonymous) @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
(anonymous) @ VM32 application-ae291f799496478302742f713e72f20a7958b7077387b87e18ab98c51ec979c4.js:243
  

要解决此问题,看来我有以下两种解决方案

1)使用data-turbolinks-track:重新加载

<%= javascript_include_tag "application", 'data-turbolinks-track': :reload, nonce: true %>

OR

2)使用会话存储为Turbolink请求重用同一随机数,这是解决此问题的正确方法吗?

Rails.application.config.content_security_policy_nonce_generator = -> request do
  # use the same csp nonce for turbolinks requests
  if request.env["HTTP_TURBOLINKS_REFERRER"].present? && request.session["mykey"].present?
    request.session["mykey"]
  else
    request.session["mykey"] = SecureRandom.base64(16)
  end
end

请在这里提出正确的解决方案!

0 个答案:

没有答案