Asp.net CSP:浏览器是否检查头中的nonce值是否与脚本标记中的nonce值匹配?
我有一个使用Ajax加载部分内容的页面。部分内容具有Asp.net CSP:浏览器是否检查头中的nonce值是否与脚本标记中的nonce值匹配?,asp.net,google-chrome,asp.net-core,microsoft-edge,content-security-policy,Asp.net,Google Chrome,Asp.net Core,Microsoft Edge,Content Security Policy,我有一个使用Ajax加载部分内容的页面。部分内容具有script标记,其nonce值与content Security Policy标头中定义的nonce不匹配 以下是完整的代码(使用asp.net core+jQuery 2.1.1) 中间件 对于每个http请求,中间件将使用nonce值注入内容安全策略头 public class CSPMiddleware { private readonly RequestDelegate _next; public CSPMiddle
script
标记,其nonce值与content Security Policy
标头中定义的nonce不匹配
以下是完整的代码(使用asp.net core+jQuery 2.1.1)
中间件对于每个http请求,中间件将使用nonce值注入
内容安全策略
头
public class CSPMiddleware
{
private readonly RequestDelegate _next;
public CSPMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.Response.Headers["Content-Security-Policy"] = $"default-src 'self'; script-src 'self' 'nonce-abc' 'unsafe-eval'";
await _next(context);
}
}
Index.cshtml
<button type="button" id="btnGetContent">Get Partial View</button>
<div id="result">
</div>
//this script on the main page will execute since nonce matches with the header
<script type="text/javascript" nonce="abc">
$(function () {
$("#btnGetContent").click(function () {
$.ajax({
type: "GET",
url: "/home/getpartialview",
processData: true,
cache: false
})
.done(function (response, textStatus, jqXHR) {
$("#result").html(response);
})
})
})
</script>
获取部分视图
//主页上的此脚本将执行,因为nonce与标头匹配
$(函数(){
$(“#btnGetContent”)。单击(函数(){
$.ajax({
键入:“获取”,
url:“/home/getpartialview”,
processData:对,
缓存:false
})
.done(函数(响应、文本状态、jqXHR){
$(“#结果”).html(回复);
})
})
})
局部视图
@System.DateTime.Now.ToString();
<button id="btn2">Click Me. I am on Partial</button>
// this script should not execute since nonce does not match
<script type="text/javascript" nonce="xyz">
$("#btn2").click(function () {
alert("foo");
})
</script>
@System.DateTime.Now.ToString();
点击我。我是局部的
//由于nonce不匹配,因此不应执行此脚本
$(“#btn2”)。单击(函数(){
警惕(“foo”);
})
我的期望是,部分视图上的click事件不应该触发,因为脚本的nonce值与标题不匹配。但是,点击事件确实会引发火灾
浏览器是否检查
内容安全策略
标题中的nonce值是否与脚本标记中的nonce值匹配?是的,浏览器检查是否与标题和脚本标记中的nonce值完全匹配。但是jQuery 2.x(无意中)使用了一种技术,通过'safe-eval'
绕过'nonce-value'
(您必须允许eval)
该框架中断了在HTML代码中放置脚本的所有逻辑
jQuery 2.x解析HTML中的所有..
标记,并将其放入动态生成的脚本标记中,或通过eval()
执行这些标记:
这就是Dropbox对jQuery 2.x执行手动检查nonce
的原因:
更多详细信息,请参见AppSec EU 2017(已倒转至所需时间)。谢谢。我想我可以决定是否需要添加
unsafe inline
,这是我最初的问题