【问题标题】:react-google-recaptcha allow CSPreact-google-recaptcha 允许 CSP
【发布时间】:2021-10-18 09:02:45
【问题描述】:

我正在使用 react js 是我使用 react-google-captcha 的一种形式,并且在构建和后端我使用提供 CSP 安全性的头盔时运行良好,并且出现了其他错误

在搜索了很多网站后,我添加了以下元标记

<meta
  http-equiv="Content-Security-Policy"
  content="script-src 'self' https://www.google.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/;
  frame-src https://www.google.com https://www.google.com/recaptcha/ https://recaptcha.google.com/recaptcha/"
/>

仍然没有运气。你遇到过这个问题吗?可以和我分享解决方案。提前致谢

在我的头盔配置中

【问题讨论】:

    标签: reactjs recaptcha content-security-policy helmet.js react-google-recaptcha


    【解决方案1】:

    这里是头盔维护者。

    发生这种情况是因为 Helmet 默认设置的内容安全策略。 Helmet 将其设置在 HTTP 标头中,该标头会覆盖您在 &lt;meta&gt; 标记中放入的内容。

    要解决您的问题,您需要配置 Helmet 的 CSP。

    MDN has a good documentation about CSP 我建议您阅读它作为背景。之后,看看Helmet's README,看看如何配置它的CSP组件。

    为了针对这个问题提供一些帮助,让我们看一下您看到的一个错误:

    Refused to load the script 'https://google.com/recaptcha/...' because it violates the following Content Security Policy directive: "script-src 'self'". ...
    

    这个错误告诉你 CSP 的 script-src 指令不允许 JavaScript 从 google.com/recaptcha 加载,因此它被阻止了。

    有几种方法可以解决这个问题:

    1. 更新您的 CSP 以允许从 Google 加载 JavaScript。你会做这样的事情:

      app.use(
        helmet({
          contentSecurityPolicy: {
            useDefaults: true,
            directives: {
              "script-src": ["'self'", "google.com"],
            },
          },
        })
      );
      
    2. 重构您的应用以避免加载验证码。可能不可能,但这是一个可用的解决方案。

    3. 禁用 CSP。这是最危险的选择,所以不推荐。

      app.use(
        helmet({
          contentSecurityPolicy: false,
        })
      );
      

    总而言之:要解决您的问题,您需要告诉 Helmet 配置您的 CSP。

    【讨论】:

    • 嗨@Evan,当我尝试解决方案时出现了同样的错误,我还尝试清除缓存等。我用新的头盔配置编辑了我上面的问题仍然没有运气
    【解决方案2】:

    非常感谢@evanHahn 配置现在正在努力解决您需要在 ss 下面的后端配置头盔的问题。

    app.use(
    helmet({
      contentSecurityPolicy: {
        useDefaults: true,
        directives: {
          "script-src": ["'self'", "https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/"],
          "frame-src": ["'self'", "https://www.google.com/recaptcha/", "https://www.gstatic.com/recaptcha/"],
        },
      },
    }));
    

    【讨论】:

    • 请不要使用截图分享代码,如果其他人有相同或类似的问题,这会使其难以使用您的答案
    猜你喜欢
    • 2021-10-13
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2021-04-01
    • 2021-11-24
    • 2021-05-16
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多