Google Fonts violates Content Security Policy

2020-02-07 17:45发布

I'm trying to use Google Fonts and I've never had any problems, but now when I try to add the CSS file on my header I get this error on the console:

Refused to load the stylesheet 'http://fonts.googleapis.com/css?family=Whatever' because it violates the following Content Security Policy directive: "style-src 'self' 'unsafe-inline'".

4条回答
【Aperson】
2楼-- · 2020-02-07 18:33

There are two things to fix here:

  • Use https for the Google fonts link (https://fonts.googleapis.com/css?family=Whatever)
  • Authorize https://fonts.googleapis.com in style-src directive and https://fonts.gstatic.com in font-src directive: "style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com"
查看更多
够拽才男人
3楼-- · 2020-02-07 18:34

If you're like me and a little confused because every answer is just saying you need to authorize a URL in a style-src directive without showing how to do it, here's the full tag:

<meta http-equiv="Content-Security-Policy" content="style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;">
查看更多
Ridiculous、
4楼-- · 2020-02-07 18:38

When working with Helmet, the following works perfectly (written in 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.
      ],
    }
  })
);
查看更多
趁早两清
5楼-- · 2020-02-07 18:40

There are multiple sources that can be given for Content-Security-Policy.

Below has clear details, which worked for me.

Depending on which content (css, img, font, media) source error you have, you can change the URL in the below.

<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>

Hope that helps.

查看更多
登录 后发表回答