Angular 14中使用Nonce实现内联样式CSP的正确实现方式咨询
Angular 14 实现CSP内联样式nonce的疑问
背景
我参考了一份Angular结合Nginx实现内联样式内容安全策略(CSP)的方案,按理解梳理出步骤后尝试适配Angular 14实现,但遇到了问题。
方案步骤梳理
- 在
index.html中添加CSP元标签:<meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 'self' 'nonce-random-csp-nonce';"> - 修改
shared_styles_host.ts的_addStylesToHost方法,为生成的style标签添加nonce属性: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'); // 添加nonce styleNodes.push(host.appendChild(styleEl)); }); }
我的Angular 14实现代码
import { eDomSharedStylesHost } from '@angular/platform-browser';// 此处导入路径存疑 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'); // 添加nonce styleNodes.push(host.appendChild(styleEl)); }); } }
问题与疑问
- 上述实现方式是否正确?
- Angular 14版本的
@angular/platform-browser中找不到可重写的_addStylesToHost导出成员,该如何处理? - ESLint持续报错:
_addStylesToHost已声明但未使用。
内容的提问来源于stack exchange,提问作者prabhat gundepalli
相关产品推荐
相关产品推荐

