如何在 connect-src(csp) 中使用 nonce 或 sha?

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

是否可以在 API 请求中使用随机数,以便 CSP 中的 connect-src 检测到它不是恶意地址?

到现在我看到nonce只能用在script-src或style-src中,不能用在connect-src中

到目前为止,我只能将 URL 列表放在 connect-src 中...

如果有人有 Angular 或 js 的例子,请分享

这就是我的 csp 的样子:

connect-src 'self' 数据:https://url wss://url 'nonce-the_nonce'; script-src 'self' 'nonce-the_nonce';

带有随机数的获取请求(这个 URL 不包含在我的 connect-src 数据 URL 列表中,我希望它与随机数一起工作):

  <script nonce="the_nonce">

    fetch(`https://url`,{method:'GET'}).then(res=>{
      console.log(res.status);
    },err=>{
      console.log(err.errorStatusCode);
    });

  </script>

我得到的错误:

拒绝连接到“https://url”,因为它违反了以下内容安全策略指令:“connect-src 'self' data: https://url wss://url 'nonce-the_nonce”。

javascript angular nginx-config sha
1个回答
0
投票

在内容安全策略 (CSP) 中,connect-src 指令可以 使用随机数或哈希。 connect-src 指令列出了允许向源发送网络请求(例如 AJAX 或 WebSocket 请求)的 URI。使用 nonce 或 hash 使浏览器能够识别请求是经过授权的并且来自可靠的来源。

如果要将随机数与 connect-src 指令一起使用,则必须为每个请求创建一个特殊的随机数值并将其包含在请求的标头中。此处显示了如何在 Angular 中创建 nonce 值的示例:

import { DomSanitizer, SafeValue } from '@angular/platform-browser';
import { SecurityContext } from '@angular/core';

// 生成随机随机数

const nonce = Math.random().toString(36).substring(2, 15);

// 使用 nonce 值创建一个 Content-Security-Policy 头

const csp = `connect-src 'self' data: https://url wss://url 'nonce-${nonce}'`;

// 清理 CSP 标头以防止 XSS 攻击

const safeCsp: SafeValue = this.sanitizer.bypassSecurityTrustHtml(csp);

// 在 HTTP 请求上设置 CSP 标头

const headers = new HttpHeaders({ 'Content-Security-Policy': safeCsp });

// 发送带有 nonce 标头的 HTTP 请求

this.http.get('https://example.com/data', { headers: headers }).subscribe(...);

在上面的示例中,CSP 标头中的 connect-src 指令补充了生成的随机随机数值。之后,清理CSP头以防止XSS攻击,并使用Angular的HttpClient发送带有nonce头的HTTP请求。

需要注意的是,如果服务器没有在 Content-Security-Policy 头中包含 nonce 值,浏览器将不会接受响应。

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