Reputation: 83
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.
Upvotes: 0
Views: 886
Reputation: 83
I was able to make it work by adding the following line of code in elements.module.ts file and adding the nonce attribute value in script tag which is used in the client application.
providers.push({ provide: CSP_NONCE, useValue: nonce_value });
This nonce_value is the backend generated unique value per page load
Upvotes: 0