【发布时间】:2021-05-05 23:50:37
【问题描述】:
我有一个使用 Ajax 加载部分内容的页面。部分内容有 script 标签,其 nonce 值与 Content-Security-Policy 标头中定义的 nonce 不匹配。
这里是完整代码(使用 asp.net core + jQuery 2.1.1)
中间件
对于每个 http 请求中间件都会注入带有 nonce 值的 Content-Security-Policy 标头
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>
局部视图
@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>
我的期望是,部分视图上的点击事件不应触发,因为脚本的 nonce 值与标题不匹配。但是点击事件确实会触发。
浏览器是否检查Content-Security-Policy 标头中的 nonce 值是否与 script 标签中的 nonce 值匹配?
【问题讨论】:
标签: asp.net google-chrome asp.net-core microsoft-edge content-security-policy