Kyle Fong
Kyle Fong

Reputation: 151

How to add preconnect and preload to content security policy?

Is it possible to add preconnect and preload to a CSP meta tag?

<!DOCTYPE html>
<html>
  <head>
<meta
      http-equiv="Content-Security-Policy"
      content="base-uri 'self'; object-src 'none'; script-src 'nonce-pb+8iY9WcWmhlEX6d1cjqA=='; style-src 'nonce-IOaKe0RIRR+SDo/VCRRk/g==' 'nonce-1akTtzYTJ2M1nq/GqmKH8Q==' 'nonce-bebsmDPpynkvU6DpcJMXOA=='"/>
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
      rel="preconnect"
      as="fetch"
      href="https://fonts.gstatic.com"
      crossorigin
    />
    <link
      rel="preload"
      as="style"
      href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;500;700&family=Roboto+Slab:wght@400;500&display=swap"
    />
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;500;700&family=Roboto+Slab:wght@400;500&display=swap"
      media="print"
      onload="this.media='all'"
      nonce="IOaKe0RIRR+SDo/VCRRk/g=="
    />

I can add 'style-src' policies, but am unsure how to add the https://fonts.gstatic.com and the https://fonts.googleapis.com domains for preconnect and preload.

Context: This may be relevant to Webpack because I am using webpack as a bundler and an index.html as a template. Second, I am building a static SPA and serving in s3 and caching in cloudfront.

I am using ideas to speed up google font load taken from https://csswizardry.com/2020/05/the-fastest-google-fonts

Upvotes: 2

Views: 1081

Answers (1)

granty
granty

Reputation: 8564

  1. Generally you can allow external stylesheets both using 'nonce-value' and/or host-source.

  2. You do not have to generate unique nonce for each script/style, you can use one generated value for all of them. But you need to generate a new nonce each page loads.

AFAIK it's impossible to provide new 'nonce-value' each time for an already generated webpack bundle. So just use host-sources instead of nonce:

<meta
  http-equiv="Content-Security-Policy"
  content="base-uri 'self'; object-src 'none';
     script-src 'self' host-source_1 host-source_2 'sha256-value_of_inline_script_1' 'sha256-value_of_inline_script_2';
     style-src 'self' https://fonts.googleapis.com;
     font-src https://fonts.gstatic.com data:;
  "/>

Notice: Use 'hash-value' for inline scripts/styles, webpack has plugins to generate those on a fly.

Upvotes: 1

Related Questions