[英]Why does CSP script-src unsafe-inline induce styling issues on my Angular webapp?
When I try to remove unsafe-inline
source for script-src
CSP my Angular webapp does not work anymore.当我尝试删除script-src
CSP 的unsafe-inline
源时,我的 Angular webapp 不再工作。
When using SCSS in Angular@12+, Angular add a property onload
on the index.html
在 Angular@12+ 中使用 SCSS 时,Angular 在index.html
上添加属性onload
<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.这会导致违反script-src
header 的 CSP unsafe-inline
源代码。
How to fix this issue and remove this "security breach" on my Angular web app?如何解决此问题并删除我的 Angular web 应用程序上的此“安全漏洞”?
Adding "inlineCritical": false
to the angular.json
solved the issue because it disable Critical CSS inlining.添加"inlineCritical": false
到angular.json
解决了这个问题,因为它禁用了 Critical CSS 内联。
"configurations": {
"production": {
"optimization": {
"styles": {
"inlineCritical": false
}
}
}
}
When the browser renders a page, it has to wait for the CSS resources to be downloaded and parsed.浏览器在渲染一个页面的时候,要等待CSS个资源被下载解析完。 It can give the (false) impression that the loading of your application is slow, and impacts the First Contentful Paint (FCP) time.它会给人一种(错误的)印象,即您的应用程序加载缓慢,并会影响 First Contentful Paint (FCP) 时间。
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).避免这种情况的一种常用技术是将 CSS 直接内联到 HTML 中,以避免额外请求(这是 Lighthouse 推荐的方法)。 But you don't want to inline all your CSS, otherwise the time to download the HTML increases.但是您不想内联所有 CSS,否则下载 HTML 的时间会增加。 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).您只想内联关键的 CSS 资源,这些资源会阻止渲染,并且您的用户会看到(您可以延迟 CSS 的 rest)。
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: Angular CLI 在 v11.1 中引入了一个新选项来帮助我们解决这个问题: inlineCSS
然后,CLI 将在后台使用critters
来提取应用程序的关键 CSS,并将它们直接内联到 HTML 中。运行ng build --prod
使用上述配置生成一个index.html
文件,其中包含提取的关键 CSS 的样式元素,并且使用异步加载通常的styles.xxxxx.css
:
<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/有关不安全内联 CSP 关键字的更多信息: https://content-security-policy.com/unsafe-inline/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.