将 google 字体 (fonts.googleapis.com) 添加到 CSP header

Adding google fonts (fonts.googleapis.com) to CSP header

我在 gitHub 页面上托管一个个人项目,并使用 cloudflare 强制执行 https。现在我想实施 CSP 政策。

我尝试将元标记添加到我的页面的头部:

<meta HTTP-EQUIV='Content-Security-Policy' CONTENT="default-src 'self' *.fonts.googleapis.com/* *.cloudflare.com/* *.fonts.googleapis.com/*;">

但我收到以下错误:

Refused to load the stylesheet 'https://fonts.googleapis.com/icon?family=Material+Icons' because it violates the following Content Security Policy directive: "default-src 'self' .fonts.googleapis.com/ .cloudflare.com/ .fonts.googleapis.com/". Note that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

这是我包含的脚本:

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
        rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Noto+Sans|Roboto" rel="stylesheet">

不会设置 *.fonts.googleapis.com/* 允许页面中的所有内容吗?

因为这是我第一次设置 CSP,这是为 github 页设置 CSP 的正确方法吗?我还没有找到这方面的任何读物。

Won't setting *.fonts.googleapis.com/* allow everything from the page?

虽然这很直观,但答案是

看的不错HTML5rocks introduction to Content Security Policy on the topic of wildcards (section Implementation details):

Wildcards are accepted, but only as a scheme, a port, or in the leftmost position of the hostname: *://*.example.com:* would match all subdomains of example.com (but not example.com itself), using any scheme, on any port.

因此,两种字体的工作 CSP 可能如下所示:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' https://fonts.googleapis.com/ https://fonts.gstatic.com/ 'unsafe-inline';">

注意 1:最好使用相应的 CSP directives。在您的情况下,您应该像这样使用 font-srcstyle-src

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; font-src 'self' https://fonts.gstatic.com/; style-src 'self' https://fonts.googleapis.com/ 'unsafe-inline';">

使用相应指令的优点是您的 CSP 现在变得非常严格。例如,您不再允许 'unsafe-inline' 作为脚本源。这意味着内联 javascript 现在被禁止了。也禁止从 https://fonts.gstatic.com/ 加载脚本,这在以前是允许的。等等...


注意 2:您可以通过使用哈希或随机数完全摆脱 'unsafe-inline' 关键字。对于这个示例,我无法完成这项工作,但如果您有兴趣,请再次查看 HTML5rocks intro