如何在 Angular 16 中为动态创建的脚本和样式添加 nonce 属性?

问题描述 投票:0回答:1

我使用 Angular 16 在应用程序中添加 Content-Security-Policy 标头以避免 XSS 攻击。我在index.html中的标签中添加了ngCspNonce属性,并在服务器端设置随机nonce值。 Angular 加载的所有样式和脚本都具有 nonce 属性。 我注意到,当外部库向页面的头部添加某些内容时,不会设置随机数。 该库首先将脚本加载到 head 部分,这会创建标记,这些标记被 CSP 设置阻止。 有什么办法可以添加缺失的随机数吗?

我的 CSP 如下所示: script-src 'self' 'nonce-random_nonce_value' style-src 'self' 'nonce-random_nonce_value'

我可以为此使用 CSP_NONCE 令牌注入吗?如果是的话怎么办?

我希望该网站能够通过 CSP 标头进行保护,而不会由于使用外部库而使用“不安全内联”或“不安全哈希”。

angular content-security-policy nonce
1个回答
0
投票

要将缺少的随机数添加到外部库动态添加的脚本中,您需要在加载外部脚本后操作 DOM。您可以使用 Angular 的 Renderer2 服务来实现此目的。以下是如何做到这一点的示例:

import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

// Inject the document object
constructor(private renderer: Renderer2, @Inject(DOCUMENT) private document: Document) { }

// This function should be called after the external library has added the script to the head section
addNonceToDynamicallyAddedScripts() {
  const scripts = this.document.querySelectorAll('script');
  
  scripts.forEach(script => {
    // Check if the script is dynamically added by the external library
    if (!script.hasAttribute('nonce')) {
      // Add the nonce attribute
      this.renderer.setAttribute(script, 'nonce', 'random_nonce_value'); // Replace with your actual nonce value
    }
  });
}

在您的组件或服务中,在外部库将其脚本加载到 head 部分后调用 addNonceToDynamicallyAddedScripts()

此代码片段检查页面上的所有

元素,并添加 nonce 属性(如果丢失)。确保将 'random_nonce_value' 替换为您的实际随机数值。

请注意,此方法假设外部库在调用

addNonceToDynamicallyAddedScripts() 之前已经加载了其脚本。如果加载是异步的,您可能需要在执行此代码之前确保库已完成加载。

请记住在您的特定用例中对此进行彻底测试,以确保它在您的 CSP 设置中按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.