如何使用nonce或sha连接src(csp)?



是否有可能将nonce与API请求一起使用,以便CSP中的connect-src检测到它不是恶意地址?

到目前为止,我看到nonce只能在script-src或style-src中使用,而不能在connect-src 中使用。到目前为止,我只能将URL列表放在connect-src…

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

就像我的csp:

connect-src 'self' data: https://url wss://url 'nonce-the_nonce';Script-src 'self' 'nonce-the_nonce';

(这个URL不包含在我的中)连接-src数据url列表,我希望它与nonce一起工作):
<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 ' nince -the_nonce"

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

如果你想在connect-src指令中使用nonce,你必须为每个请求创建一个特殊的nonce值,并将其包含在请求的头中。下面是如何在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指令补充了一个随机生成的nonce值。之后,CSP头被清理以防止XSS攻击,然后使用Angular的HttpClient发送带有nonce头的HTTP请求。

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

最新更新