You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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));
    });
  }
}

问题与疑问

  1. 上述实现方式是否正确?
  2. Angular 14版本的@angular/platform-browser中找不到可重写的_addStylesToHost导出成员,该如何处理?
  3. ESLint持续报错:_addStylesToHost已声明但未使用。

内容的提问来源于stack exchange,提问作者prabhat gundepalli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 07:48:30