Setting up Content Security Policy for Google Fonts
TL;DR: Use the following snippet to setup CSP for Google Fonts:
style-src 'self' https://fonts.googleapis.com;
What is CSP?
Content Security Policy allows you to define a set of rules that control what resources are being loaded on your website. This is a great way to prevent malicious scripts from being loaded on your website, and to prevent XSS attacks.
Sometimes it can stand in your way. Does that look familiar?
Refused to load the stylesheet 'https://fonts.googleapis.com/css2?...' because it violates the following Content Security Policy directive: "style-src 'self'".
Note that 'style-src-elem' was not explicitly set, so 'style-src' is used as a fallback.
How to fix such an error?
Fixing Google Fonts issues
Let's start with the simplest CSP.
As you probably know, the default-src directive serves as a fallback for a bunch of other directives.
This CSP snippet prevents any resource being loaded from any host other than itself. But Google Fonts are hosted on a different domain, so we need to specifically allow this domain for stylesheets.
default-src 'self'; style-src 'self' https://fonts.googleapis.com
OK, now we get the next error.
It has refused to load the font 'https://fonts.gstatic.com/s/...' because it violates the following Content Security Policy directive: "default-src 'self' https://fonts.googleapis.com". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.
It happens because we only allowed the browser to load the CSS file. But that stylesheet includes references to the actual font files. When the browser tries to download them, it gets refused.
Let's add it as well.
default-src 'self'; style-src 'self' https://fonts.googleapis.com; font-src https://fonts.gstatic.com
If you want to learn about CSP - MDN is a great resource.
If you need to track and analyze CSP reports, try CSP Hero.