Google字体违反了内容安全政策

Jos*_*ría 40 html css http google-font-api content-security-policy

我正在尝试使用谷歌字体,我从来没有遇到任何问题,但现在当我尝试在我的标题上添加CSS文件时,我在控制台上收到此错误:

拒绝加载样式表,'http://fonts.googleapis.com/css?family=Whatever'因为它违反了以下内容安全策略指令:"style-src 'self' 'unsafe-inline'".

小智 69

这里有两件事需要解决:

  • 使用https作为Google字体链接(https://fonts.googleapis.com/css?family=Whatever)
  • 授权https://fonts.googleapis.comstyle-src指令,并https://fonts.gstatic.comfont-src指令:"style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com"

  • 对于其他人来看这个答案,不要复制'不安全的内联',因为它没有任何正当理由降低安全性 - 字体不需要工作.它存在的唯一原因是因为OP在原始代码中有它.使用`style-src'self'https://fonts.googleapis.com; font-src'self'https://fonts.gstatic.com;` (17认同)
  • 什么是`data:`for? (4认同)
  • @KevinLee 如果您将评论转化为答案,我会赞成。 (3认同)
  • `允许数据:URI 用作内容源。` 来自 https://developer.mozilla.org/en/docs/Web/Security/CSP/CSP_policy_directives#Data (2认同)

Owe*_*wen 26

如果你像我一样有点困惑,因为每个答案都只是说你需要在style-src指令中授权URL 而不显示如何操作,这里是完整的标记:

<meta http-equiv="Content-Security-Policy" content="style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;">
Run Code Online (Sandbox Code Playgroud)


Dan*_*cki 6

使用Helmet 时,以下效果完美(用 TypeScript 编写):

import * as express from 'express';
import { Express } from 'express';
const helmet = require('helmet');
const expressApp: Express = express(); // Create Express instance.

expressApp.use(
  helmet.contentSecurityPolicy({
    directives: {
      fontSrc: [
        "'self'", // Default policy for specifiying valid sources for fonts loaded using "@font-face": allow all content coming from origin (without subdomains).
        'https://fonts.gstatic.com' // Google Fonts.
      ],
      styleSrc: [
        "'self'", // Default policy for valid sources for stylesheets: allow all content coming from origin (without subdomains).
        'https://fonts.googleapis.com' // Google Fonts.
      ],
    }
  })
);
Run Code Online (Sandbox Code Playgroud)


Man*_*ddy 5

可以提供多种来源Content-Security-Policy

下面有明确的细节,对我有用。

根据您遇到的内容(css,img,字体,媒体)源错误,可以在下面更改URL。

<html>

<head>

  <meta http-equiv="Content-Security-Policy"
    content="
      default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; 
      style-src   'self' https://fonts.googleapis.com;
      font-src    'self' data: https://fonts.gstatic.com;
      img-src     'self' data: content:;
      media-src   *;
            "
  />

 <title>My page title</title>

</head>

<body>
  some text
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助。