配置CSP nonce后脚本加载失败,控制台报错寻求解决方案
问题分析与解决
问题描述
已在ASP.NET Core中配置内容安全策略(CSP)并使用nonce机制:
app.Use(async (context, next) => { var ByteArray = new byte[20]; using (var Rnd = RandomNumberGenerator.Create()) { Rnd.GetBytes(ByteArray); } var nonce = Convert.ToBase64String(ByteArray); context.Items.Add("ScriptNonce", nonce); context.Response.Headers.Add("Content-Security-Policy", new[] { string.Format("script-src-elem 'self' 'nonce-{0}'", nonce) }); await next(); });
页面中引入第三方脚本:
<script nonce='@nonceValue' src="https://sl.setrowid.com/index.js.php?mkodu=2700" crossOrigin="anonymous"></script>
但控制台出现两类错误:
拒绝加载脚本'https://push.setrowid.com/v3/push_loader.php?mkodu=2700',因为它违反了Content Security Policy指令:"script-src-elem 'self' 'nonce-liYA5nqhRREBU3P1Wg/WrvVxmGQ='"。
拒绝执行内联脚本,因为它违反了Content Security Policy指令:"script-src-elem 'self' 'nonce-liYA5nqhRREBU3P1Wg/WrvVxmGQ='"。需要使用'unsafe-inline'关键字、哈希('sha256-Ryk1bebqkZRJKst9ISGjr+0FqT27dlA4N8+D6EPUtKo=')或nonce('nonce-...')才能启用内联执行。
解决方案
1. 允许第三方脚本域名
第一个错误是因为https://push.setrowid.com未被加入CSP的允许列表,需将该域名添加到script-src-elem指令中,若https://sl.setrowid.com也存在被拦截风险,可一并加入:
context.Response.Headers.Add("Content-Security-Policy", new[] { string.Format("script-src-elem 'self' 'nonce-{0}' https://push.setrowid.com https://sl.setrowid.com", nonce) });
2. 处理未授权的内联脚本
第二个错误源于页面中存在未被CSP允许的内联脚本,可通过两种方式解决:
- 给内联脚本添加nonce:找到页面中的内联脚本,为其添加与第三方脚本一致的
nonce='@nonceValue'属性,示例:
<script nonce='@nonceValue'> // 内联脚本内容 </script>
- 使用哈希值授权内联脚本:若无法给内联脚本添加nonce,可将错误提示中的哈希值加入CSP指令:
context.Response.Headers.Add("Content-Security-Policy", new[] { string.Format("script-src-elem 'self' 'nonce-{0}' https://push.setrowid.com https://sl.setrowid.com 'sha256-Ryk1bebqkZRJKst9ISGjr+0FqT27dlA4N8+D6EPUtKo='", nonce) });
注意:若内联脚本内容发生修改,对应哈希值会失效,需重新生成并替换。
内容的提问来源于stack exchange,提问作者Erkan Kabil
相关产品推荐
相关产品推荐

