ruby-on-rails 内容安全策略:页面设置阻止加载资源,

carvr3hs  于 4个月前  发布在  Ruby
关注(0)|答案(1)|浏览(82)

我正在尝试使用Adding Google sign-in resource在我的Web应用程序中设置Google登录
我将下面的代码添加到相关的html文件中

<html>
  <body>
      <script src="https://accounts.google.com/gsi/client" async defer></script>
      <div id="g_id_onload"
         data-client_id="YOUR_GOOGLE_CLIENT_ID"
         data-login_uri="https://your.domain/your_login_endpoint"
         data-auto_prompt="false">
      </div>
      <div class="g_id_signin"
         data-type="standard"
         data-size="large"
         data-theme="outline"
         data-text="sign_in_with"
         data-shape="rectangular"
         data-logo_alignment="left">
      </div>
  </body>
</html>

字符串
当我尝试在浏览器中查看Web应用程序的页面时。我看不到Google登录按钮,当我检查页面时,我看到以下两个错误

Content Security Policy: The page’s settings blocked the loading of a resource at https://accounts.google.com/gsi/client (“script-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/mini-profiler-resources/includes.js?v=35a79b300ab5afa978cb59af0b05e059 (“script-src”).

的数据
我尝试查看内容安全策略上的资源来解决此问题,发现添加源允许列表是解决方案。请参阅this resource以了解我在哪里找到此解决方案。我具体在哪里添加此允许列表?我应该添加什么确切的代码?如果我走错了方向,请向我指出有助于解决此问题的资源或说明。
我的开发环境是ubuntu 20.04,我使用的浏览器是Mozilla Firefox,我正在开发我的第一个ruby on rails应用程序。
感谢您的时间和努力。

hgqdbh6s

hgqdbh6s1#

内容安全策略是Web应用程序安全性的附加层,大多数现代Web浏览器都支持它。它的主要目标是减轻对现代Web应用程序的一系列客户端攻击(查看此文档以获取更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)。
在应用程序中包含内容安全策略有两种方法。第一种是在服务器的浏览器中包含HTTP头。假设您使用的是Ruby on Rails,可能有几种方法可以设置此头。
您可以在代码级别配置CSP。您必须修改文件:config/initializers/csp.rb

SecureHeaders::Configuration.default do |config|
  config.csp = {
    default_src: %w('self'), # self-hosted resources allowed by default 
    script_src: %w(https://accounts.google.com), #here you have to include origins of all of your scripts 
    connect_src: %w('self'),
    img_src: %w('self'),
    font_src: %w('self'),
    base_uri: %w('self'),
    style_src: %w('unsafe-inline'),
    form_action: %w('self'),
    report_uri: %w(/mgmt/csp_reports)
  }
end

字符串
我不是Ruby开发人员,所以我建议使用该资源获取更多信息:https://bauland42.com/ruby-on-rails-content-security-policy-csp/
您还可以使用以下Meta标记在HTML级别设置CSP:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src https://accounts.google.com; child-src 'none'; object-src 'none'">


另一种方法是在Web服务器级别设置CSP头。例如,在nginx中,您可以这样设置(在/etc/nginx/sites-enabled/your_confserver {}块中(或其他路径-取决于您的nginx配置):

add_header Content-Security-Policy "default-src 'self'; script-src https://accounts.google.com;" always;


请记住,使用default-src 'self'指令意味着,您还必须在Content-Security-Policy中包含所有外部资源-包括字体,图像,样式等。

相关问题