what is the right Implementation for inline styles CSP in Angular 14 using nonce approach

323 Views Asked by At

I am following this solution: https://dev.to/ferdiesletering/how-to-implement-an-inline-styles-content-security-policy-with-angular-and-nginx-2ke2

As per my understanding,

  1. Add below code to index.html

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'nonce-random-csp-nonce';">

  1. Add nonce to style tag

We copy the shared_styles_host.ts and modify the _addStylesToHost method.

private _addStylesToHost(
    styles: Set<string>,
    host: Node,
    styleNodes: Node[]
  ): void {
    styles.forEach((style: string) => {
      const styleEl = this._doc.createElement('style');
      styleEl.textContent = style;
      styleEl.setAttribute('nonce', 'random-csp-nonce'); // Add nonce
      styleNodes.push(host.appendChild(styleEl));
    });
  }

My implementation for angular 14,

Below is my shared_styles_host.ts

However is this even the right implementation?

import { eDomSharedStylesHost } from '@angular/platform-browser';// what to import from here

export class CustomDomSharedStylesHost {
private _doc:any;

private _addStylesToHost(
    styles: Set<string>,
    host: Node,
    styleNodes: Node[]
  ): void {
    styles.forEach((style: string) => {
      const styleEl = this._doc.createElement('style');
      styleEl.textContent = style;
      styleEl.setAttribute('nonce', 'random-csp-nonce'); // Add nonce
      styleNodes.push(host.appendChild(styleEl));
    });
  }
}

enter image description here There is no export member_addStylesToHost method to overwrite from @angular/platform-browser in angular 14 version as shown in the screenshot. Also eslint keeps on throwing error of: _addStylesToHost declared but never used

0

There are 0 best solutions below