Styles imported through angular.json blocked by Content-Security-Policy script-src: self

725 views Asked by At

I have imported couple of css and scss files through angular.json styles array, this eventually added

<link rel="stylesheet" href="styles.44408b7ba7c0e916.css" media="all" onload="this.media='all'">

under <body>. I have content-security-policy: object-src 'none'; script-src 'self', which is blocking the above <link> from loading and hence application not working. The error is as below,

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.

angular.json

enter image description here

link tag

enter image description here

error in console

enter image description here

I see adding 'unsafe-inline' to CSP will solve the problem but I cannot go with this solution as this is unsafe.

Please suggest me any other solution which is not a threat to security.

Also please throw some light on why css is being blocked by script-src policy.

2

There are 2 answers

0
Halvor Sakshaug On

The error says it refused to execute the inline event handler, which would be onload="this.media='all'" at the end of your tag. You should rewrite this as an event listener in an allowlisted script.

0
Karna On

This one helped to resolve my issue,

Found how to disable the inlineCritical styles https://angular.io/guide/workspace-config#styles-optimization-options

In angular.json in the build configuration Instead of

"optimization": true

Replace with

"optimization": {
  "scripts": true,
  "styles": {
    "minify": true,
    "inlineCritical": false
  },
  "fonts": true
},