如何动态替换 Azure 上托管的 Angular 中的 ngCspNonce 值

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

我有一个托管在 Azure 中的 Angular 14 应用程序。我正在应用程序中实施内容安全策略。我不想使用“unsafe-inline”来加载第三方内联样式。我在 Angular 网站上点击了此链接https://angular.io/guide/security#content-security-policy,但我不确定在 Azure 提供索引之前我必须在 Azure 中做什么来替换 ngCspNonce 属性的值.html 给用户。任何帮助,将不胜感激。谢谢你。

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

在 Azure 向用户提供

ngCspNonce
之前替换
index.html
属性的值。您可以修改 Angular 应用程序构建过程,以在构建阶段将随机数值直接注入到
index.html
中。

实现这一目标的方法如下: index.html

<!doctype  html>
<html  lang="en">
<head>
<meta  charset="utf-8">
<title>Your Angular App</title>  
<meta  http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline';">
<script>
window.__nonce__ = '{{ nonceValue }}';
</script>
</head>
<body>
<app-root></app-root>
</body>
</html>

在 Angular 应用程序的代码中(例如,

app.component.ts
),您可以动态生成随机数值并将其绑定到
nonceValue
属性:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  title = 'dynamicNonce';
  nonceValue!: string;

  constructor() {}

  ngOnInit() {
    this.nonceValue = this.generateRandomNonce();
  }

  private generateRandomNonce(): string {
    const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    const nonceLength = 16;
    let result = '';

    for (let i = 0; i < nonceLength; i++) {
      const randomIndex = Math.floor(Math.random() * charset.length);
      result += charset.charAt(randomIndex);
    }

    return result;
  }
}

这是

src/app/app.component.html
文件的完整内容,其中包含使用
<div>
提供的
nonceValue
元素 属性绑定来动态设置随机数值,这允许根据应用程序的内容安全策略 (CSP) 执行脚本。:

<div  [attr.ngCspNonce]="nonceValue">
<!-- Your app content here -->
<h1>Welcome to My Angular App!</h1>
<p>This is a sample content.</p>
<p>Nonce Value: {{ nonceValue }}</p>  <!-- Display the nonce value -->
</div>

将您的代码部署到 Web 应用程序:

enter image description here

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