Content Security Policy with Angular >= 8

Viewed 7457

How to correctly implement CSP (Content Security Policy) with Angular >= 8?

I tried something like:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'; style-src 'self'; img-src 'self';" />

On the console, I get the following errors:

enter image description here

To compile I've used the options below without success:

npm build --prod npm run build --prod npm build --aot --prod

3 Answers

you can set your own source beside 'self' source specialy for fonts and icones

<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://kit.fontawesome.com 'nonce-YLMZop38Ktla8/hmmA==' 'unsafe-eval' ;style-src  'self' 'unsafe-inline' https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com https://cdn.syncfusion.com; ">

The best thing to do is create a web.config file in src the file should contain the below. then you build the file so it is in your dist

<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="./index.html" />
      </rule>
    </rules>
  </rewrite>
  <httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="DENY" />
<add name="X-XSS-Protection" value="1; mode=block" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="Content-Security-Policy" value="default-src 'self' 'unsafe-inline' 'unsafe-eval' https://yoururl.com;" />
<add name="Permissions-Policy" value="fullscreen=()"/>
<add name="Referrer-Policy" value="no-referrer" />
<add name="Cache-control" value="no-store" />
<add name="Pragma" value="no-cache" />
<add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains; preload" />
</customHeaders>
</httpProtocol>
</system.webServer>

</configuration>

Add the meta tag

<meta http-equiv="Content-Security-Policy" content="YOUR_CSP">

in the head of the index.html file

Related