简体   繁体   中英

Why does CSP script-src unsafe-inline induce styling issues on my Angular webapp?

The issue:

When I try to remove unsafe-inline source for script-src CSP my Angular webapp does not work anymore.

What is the root cause of this issue?

When using SCSS in Angular@12+, Angular add a property onload on the index.html

<link rel="stylesheet" href="styles.672c1ac3d6da8cc311a2.css" media="print" onload="this.media='all'">

This results in a violation of the CSP unsafe-inline source for script-src header.

How to fix this issue and remove this "security breach" on my Angular web app?

The solution:

Adding "inlineCritical": false to the angular.json solved the issue because it disable Critical CSS inlining.

    "configurations": {
        "production": {
          "optimization": {
            "styles": {
              "inlineCritical": false
            }
          }
        }
      }

Why Angular does that?

When the browser renders a page, it has to wait for the CSS resources to be downloaded and parsed. It can give the (false) impression that the loading of your application is slow, and impacts the First Contentful Paint (FCP) time.

A common technique to avoid that is to inline the CSS directly in the HTML, to avoid an extra request (this is what Lighthouse recommends). But you don't want to inline all your CSS, otherwise the time to download the HTML increases. You just want to inline critical CSS resources, the ones that blocks the rendering, and that your user will see (you can defer the rest of CSS).

The Angular CLI introduces a new option in v11.1 to help us with this: inlineCSS The CLI will then use critters under the hood to extract the critical CSS of your application, and inline them directly in the HTML. Running ng build --prod with the above configuration produces an index.html file with a style element containing the critical CSS extracted, and the usual styles.xxxxx.css is loaded asynchronously using:

<link rel="stylesheet" href="styles.3d6bb69e3d075769b349.css" media="print" onload="this.media='all'">

For more informations about the unsafe-inline CSP keyword: https://content-security-policy.com/unsafe-inline/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM