Content Security Policy (CSP)
Examples


Example Using Google Fonts with a Content-Security-Policy

Find out what directives are needed to use google fonts with a content security policy (CSP)?

You're going to need to specify at least two CSP directives, the style-src and the font-src directive.

The style-src directive

Google fonts is typically served via a link tag, you might load a stylesheet such as:

<link href="https://fonts.googleapis.com/css?family=Pacifico&display=swap" rel="stylesheet">

In order for Content-Security-Policy to even load this CSS file, you will need to add fonts.googleapis.com to your style-src directive.

Your policy might look like this:

style-src fonts.googleapis.com

Without such a policy, we would get an error in our browser, for example:

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

The font-src directive

Next we need to use a font-src directive to allow the actual font-face source file. In the case of Google fonts these font files are served from fonts.gstatic.com, this means we need the following in our content security policy:

font-src fonts.gstatic.com

Without this we might get an error in the console such as:

Refused to load the font 'https://fonts.gstatic.com/s/font-name/v16/file-name.woff2' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

Putting it all together

A full Content-Security-Policy header for Google Fonts might look like this:

Content-Security-Policy: default-src 'self';font-src fonts.gstatic.com;style-src 'self' fonts.googleapis.com
CSP Developer Field Guide

CSP Developer Field Guide

Want to learn the ins and outs CSP? Grab a copy of the CSP Developer Field Guide. It's a short and sweet guide to help developers get up to speed quickly.

Grab a Copy

Struggling to stay on top of security advisories?

Advisory Week is a weekly roundup of all the security advisories published by the major software vendors.