CSP nonce not working in dot net angular application

67 views Asked by At

I am a freelance and working on frontend application where we have content security policy is applied on our application which is developed in angular 16. earlier we have applied Unsafe-evel and Unsafe-inline to allow inline scripts and contents but now we need to apply nOnce in which we need to generate random number and set it in the header of our application.

For this purpose, I have created a sample angular application and generate random number token using dot net api and call this api from angular application to get that random number. after this I have set this random number in the header of index.html and this solution is working for my sample application but throwing error in my main application which is much bigger and having multiple contents to load.

please let me what I need to apply so that nonce work properly in my application.

My code (app.component.ts)

private setCSP(): void {
    const cspMeta = this.renderer.createElement('meta');
    this.nonce = "nonce-YvY2gYXxZl1GW8GkCK9x8GXoZYV5EJAy";
    this.renderer.setAttribute(cspMeta, 'http-equiv', 'Content-Security-Policy');
    this.renderer.setAttribute(cspMeta, 'content', `default-src 'self'; style-src 'self';img-src 'self' data:; font-src 'self'; script-src self; 'nonce-${this.nonce}'`);
    this.renderer.appendChild(this.document.head, cspMeta);
  }
getNonce() {
    this.http.get<any>('/weatherforecast').subscribe(
      (result) => {
       
        console.log(result.nonce);
        this.nonce  = result.nonce;
 
        const script = this.renderer.createElement('script');
        const text = this.renderer.createText(`window.dynamicValue = '${this.nonce}';`);
        this.renderer.appendChild(script, text);
        this.renderer.appendChild(this.document.head, script);
 
      },
      (error) => {
        console.error(error);
      }
    );
  }
 
  title = 'NONCE';
}

ngOnInit() {
    //  this.getNonce();
    this.nonce = this.generateNonce();
    this.setCSP();
  }

Code:(index.html)

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>NonceDemoApp</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    
</head>
<body>
    <app-root></app-root>
</body>
</html>

Error Message attached here: enter image description here

I tried to generate nonce token using server and front end and passing this value to header in index.html and it is working perfect in my sample angular application but not working in my main application on which I am working

0

There are 0 answers