![](/img/trans.png)
[英]CSP - How to solve style-src unsafe-inline -when having dynamically positioned page elements
[英]How to solve “violate CSP directive: ”default-src 'self'" in Angular 8?
我們在客戶服務器上部署了一個 Angular 8 單頁 web 應用程序。 他們將 CSP 指令之一設置為:default-src 'self'。 我們使用ng build --prod
Angular 應用程序,就像任何其他 Angular 應用程序一樣。 部署后,我們收到此錯誤:
main-es2015.47b2dcf92b39651610c0.js:1 Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.
在瀏覽器上查看html
代碼,我看到如下內容:
如您所見,Angular 實際上使用標簽<style>
來為 css 服務(如果我錯了,請糾正我)。 這違反了問題中提到的 CSP 指令。
在搜索之后,我認為 Angular/React 在處理這個問題方面相當糟糕,這些框架沒有考慮到 CSP。 您可以查看 Angular github 頁面,這是一個未解決的問題。 現在我正在尋找一種解決方案來克服這個問題,當然改變 CSP 策略不是一種選擇,因為客戶不想這樣做。
如何告訴 Angular 不要在生產中使用標簽<style>
來服務 css? I think to make it works we need to set Angular in a way that it will load the css files, and then use styles in those files instead of injecting <style>
into html
which causes CSP issue.
編輯 1 :我們的項目正在使用scss
。
編輯 2 :搜索后,我發現 Angular 將使用<style>
元素將組件的 styles 注入 DOM。 如此處所示:
現在我有了一個想法,因為每個組件的樣式都會通過<style>
元素注入到 DOM 中,我們可以通過將所有組件的樣式.scss
文件捆綁到單個style.scss
文件中來防止這種情況發生。 從上圖中你可以看到我們總是有一個空的<style>
元素,所以如果這樣的話,我們最終將只有一個<style>
元素和一個鏈接到我們的全局樣式scss
文件的<link>
元素。 在頁面被瀏覽器渲染之前,我們可以有多種方法來刪除那個空的<style>
元素。
現在我堅持配置自定義 webpack 來實現這一點。 We cant use ng eject
to get the webpack.config.js
file since Angular CLI 6. I've been using Angular CLI 8 so the only way for me to add custom configuration into Webpack is to use custom-webpack
npm. I cant find a good config file that has the same output as my desire, please help if you know how to config webpack to bundle all component's styles scss
files in Angular into a global scss
file.
我認為這對於我的問題來說是一個可以接受的答案:
首先,我的建議是遠離使用styleUrls
。 Angular 將使用<style>
元素將組件的 styles 注入到 DOM 中。 其次,如果可能的話,您應該了解/詢問部署服務器/環境上的 CSP 策略。 我一直在做什么來解決這個問題(我的項目相對較小,只有幾十個組件):
復制(一個一個)組件的相關鏈接,將它們放入angular.json
,在styles
屬性中。 這是因為 Angular 會將此屬性中的所有 styles 捆綁為單個css/scss
文件。 我一個一個地復制,因為css/scss
文件首先設計為與 Angular 視圖封裝一起使用。 將它們全部集中到一個地方可能會引入意想不到的問題,這會破壞 UI。 每當復制組件樣式並放入styles
時,我都會檢查 UI 是否因此而中斷。 如果發生此類問題,這將幫助我縮小根本原因。
對於每個組件,在將其組件樣式文件的相對路徑復制到styles
,我刪除了@Component
中的styleUrls
。 這可以防止 Angular 將<style>
注入 DOM。
注意事項:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.