Seeking an appraoch to set ngCSPNonce or CSP_NONCE in Angular 18 for Angular Web...

Discussão em 'Angular' iniciado por VKJava, Setembro 13, 2024.

  1. VKJava

    VKJava Guest

    I have written an Angular custom element like below

    customElements.define('my-comp', createCustomElement(BasicComponent, config));

    and will provide as js file after build using npm run build-elements so that the other client applications can add this in the script tag and use this my-comp in their code like below,

    index.html of client application

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>client application</title>
    <script type="text/javascript" src="<domain>/myjsfile.js"></script>
    </head>
    <body >
    <my-comp></my-comp>
    </body>
    </html>


    This was working fine for the clients until we impose CSP and removed unsafe-inline. After removing unsafe-inline from csp and added nonce for each page, these client pages are not rendered properly (rendered misaligned/without styles applied). This is because Angular generates lot of styles inline as part of rendering my-comp and adds to the head tag dynamically, those styles tags were missing nonce attribute.

    So, how can we set the nonce value especially for the custom elements so that the angular generated dynamic styles are applied with nonce attribute?

    We are using Angular 18 and client application can send the nonce value as window param.

    Please note that, we have added ngcspnonce in the app root as <app-root ngCspNonce="random-csp-nonce"></app-root> and that makes our application to run fine as a standalone with nonce added for all the styles tags in the head section. In this case, nonce is generated on the server side and substituted in the meta tag of the index page for further use in the Angular code.

    But, we couldn't make it work for Angular custom elements.

    Continue reading...

Compartilhe esta Página