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

只愿长相守 提交于 2020-01-12 09:44:41

问题


I am hosting a personal project on gitHub pages, and using cloudflare to enforce https. Now I would like to implement a CSP policy.

I tried adding meta tag to the head of my page:

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

But I am getting the following error:

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.

This are the scripts that I am including:

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

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

Since this is the first time I am setting a CSP is this the correct way to set it for github pages? I have not found any reading on this yet.


回答1:


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

Although this would be intuitive, the answer is no.

See the pretty good 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.

So a working CSP for the two fonts could look something like this:

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

Note 1: It's a good practice to use the corresponding CSP directives. In your case you should use the font-src and style-src like so:

<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';">

The advantage of using the corresponding directives is that your CSP gets pretty restrictive now. F.e. you're not allowing 'unsafe-inline' for script sources anymore. This means inline javascript is now forbidden. It's also forbidden to load scripts from https://fonts.gstatic.com/, which was allowed before. And so on...


Note 2: You can get rid of the 'unsafe-inline' keyword at all by using a hash or a nonce. I have not been able to make this work for this example but if you're interested, just take a look at the HTML5rocks intro again.



来源:https://stackoverflow.com/questions/42369075/adding-google-fonts-fonts-googleapis-com-to-csp-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!