我将jQuery从2.1.1升级到3.5.1,我开始发现jQuery存在这个问题
拒绝执行内联脚本,因为它违反了以下内容安全策略指令:" script -src 'self‘nonce YURLOAQRrIwdGEqYSSpHx9YSWDM.’不安全-eval‘“。要么是‘不安全-内联’关键字,要么是散列('sha256-2mvMk0Nvn96VqS1UEmAZSVSEkK0CkPN....'),,要么是“不安全-.”)需要启用内联执行。
我不想使用“不安全的内联”。
2017年至2018年,这里、这里和这里记录了这一问题。我认为这个问题现在已经在jQuery 3.5.1中解决了,除非我遗漏了什么。
我的应用程序是用.NET核心5开发的。
Index.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/lib/jquery/3.5.1/jquery.min.js" asp-add-nonce="true"></script>
</head>
<body>
<button type="button" id="btnGetContent">Get Content</button>
<div id="result">
<partial name="_Test" />
</div>
<script src="~/js/index.js"></script>
</body>
</html>_Test.cshtml局部视图
@System.DateTime.Now.ToString();
<script type="text/javascript" asp-add-nonce="true">
// partial view specific inline script
</script>index.js
$(function () {
$("#btnGetContent").click(function () {
$.ajax({
type: "GET",
url: "/test/getcontent",
processData: true,
cache: false
})
.done(function (response, textStatus, jqXHR) {
// in browser's console I notice the error at this line
$("#result").html(response);
})
})
})控制器
public class TestController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult GetContent()
{
return PartialView("_Test");
}
}CSP策略
"default-src 'none'; script-src 'self' 'nonce-{0}' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; child-src 'self';"我有自定义的asp-add-nonce标记助手和一个现在的中间件。**对于每个请求**,标记助手和中间件分别向脚本标记和CSP策略中注入新的当前值,这一直很好。
在我将jQuery升级到3.5.1之后,看起来jQuery在脚本标记中也需要一个值,所以我在标题中添加了asp-add-nonce="true"
<script src="~/lib/jquery/3.5.1/jquery.min.js" asp-add-nonce="true"></script>
问题
我认为这是个问题,因为每个http请求都会创建一个值,而且每个页面只加载一次jQuery。Get Content请求创建新的值,当然,这个值与注入到jQuery脚本标记中的原始值不匹配。所以我们得到了错误Refused to execute inline script...
是否可以在不向jQuery的脚本标记中添加nonce的情况下解决这个问题?
更新1
在查看了通过浏览器提交的CSP报告之后,它揭示了更多的细节。被违反的指令实际上是script-src-elem。我的CSP政策甚至没有这个指令。此指令可在CSP 3版本中使用。不确定为什么浏览器要在jQuery上错误地执行此指令。

更新2
您可以使用下载储存库来重新生成该问题。
发布于 2021-05-06 17:19:29
好吧,基于我的相关问题这里和这里,我想我必须为jQuery 3.1+添加script-src unsafe-inline才能在下面的场景中正常工作
1>You正在使用jQuery 3.1+
2>jQuery是在_layout页面或主页上添加的,因此它在开始时只加载一次。
3>You正在使用AJAX加载部分内容。
在nonce方法中,建议对每个http请求使用唯一的nonce。但他的方法在这里行不通。因为AJAX调用在头中会得到不同的时间。因此,之后的任何jQuery调用都不能工作。
对我来说,它是使用2.1.1的,因为jQuery 2.x parses all <script>...</script> tags from the HTML and puts it in a dynamically generated script tag or executes those through eval( ) 详细信息和我有script-src nonce-xyz unsafe-eval
https://stackoverflow.com/questions/67377168
复制相似问题