Google reCAPTCHA v2 遇到 CSP14312 错误资源在 Microsoft Edge 中被阻止

Google reCAPTCHA v2 encountering CSP14312 error resource blocked in Microsoft Edge

我在我的网站上使用严格的 CSP,我使用 Google reCAPTCHA v2(复选框),但是,该复选框在其他浏览器中呈现,但在 Microsoft Edge 中不呈现,特别是 Microsoft Edge 44.18362.449.0。但是当使用 Microsoft Edge 85.0.564.51 时,复选框被正确加载。

下面是我的 CSP 配置:

default-src 'self' https://*.olark.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' 'nonce-$nonce_value' https://*.olark.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha 'strict-dynamic'; style-src 'self' 'unsafe-inline' 'nonce-$nonce_value' https://*.olark.com; img-src 'self' data: https://*.olark.com; font-src 'self'; child-src 'self' https://*.olark.com; object-src 'none'; frame-src 'self' https://www.google.com/recaptcha;

下面是控制台中使用 Microsoft Edge 44.18362.449.0 的警告:

CSP14312: Resource violated directive 'script-src...' Resource will be blocked.

以下是使用 Microsoft Edge 85.0.564.51 时控制台中的警告:

Tracking Prevention blocked access to storage for <URL>.

如何解决该问题,以便正确呈现复选框?

我认为您在 https://www.gstatic.com/recaptcha 之后错过了一个 /。那么 Edge Legacy 就无法到达该路径下的资源。它可以在 Edge Chromium 中工作,Chrome 可能是因为它们处理 url 路径的规则与在 Edge Legacy 中不同。

我添加了 / 它可以在 Edge Legacy 中正常运行。我使用如下代码:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' https://mysite/; script-src 'self' 'unsafe-inline' 'unsafe-eval' 'nonce-$nonce_value' https://mysite/ https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ 'strict-dynamic'; style-src 'self' 'unsafe-inline' 'nonce-$nonce_value' https://mysite/; img-src 'self' data: https://mysite/; font-src 'self'; child-src 'self' https://mysite/; object-src 'none'; frame-src 'self' https://www.google.com/recaptcha/;" />
    <title>reCAPTCHA demo: Simple page</title>
    <script nonce="$nonce_value" src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="" method="post">
        <label for="name">Name:</label>
        <input name="name" required><br />
        <label for="email">Email:</label>
        <input name="email" type="email" required><br />
        <div class="g-recaptcha" data-sitekey="mykey"></div>
        <input type="submit" value="Submit" />
    </form>
  </body>
</html>

Edge Legacy 中的结果:

规则如下:

default-src https://www.gstatic.com/recaptcha 'strict-dynamic' 'nonce-value'

你有两个烦恼:

  1. 当您省略尾部斜杠时,CSP 会将 /recaptcha 视为文件名(而不是目录),并只允许加载此文件。如果 https://www.gstatic.com/recaptcha/ CSP 将 /recaptcha/ 视为目录,并允许加载嵌套在其中的任何 directiries/files。
  2. Firefox 有一个 old bug,因此它不支持 'strict-dynamic' 也不支持 'nonce-value'default-src 指令中。 对于这些标记,您需要使用 script-src

PS:不要忘记在 'nonce-$nonce_value' 标记而不是 $nonce_value 变量中每次插入一个新的 server-generated 随机数。

PPS: 您还需要将 host-sources: https://script.tapfiliate.com https://fonts.googleapis.com 添加到您的 CSP 规则中。