【发布时间】:2019-03-01 09:14:11
【问题描述】:
我的问题似乎很简单,我觉得我遗漏了一些非常明显的东西;但我无法确定为什么脚本元素上的 Nonce 属性没有填充,而是保留了空字符串。
我决定使用 HttpContext 中的 Items 集合来存储 nonce,因为据我所知,它是每个请求的。
Startup.Configure(IApplicationBuilder app, IHostingEnvironment env)
...
app.Use(async (context, next) => { //CSP
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] nonceBytes = new byte[32];
rng.GetBytes(nonceBytes);
string nonce = Convert.ToBase64String(nonceBytes);
context.Items.Add("ScriptNonce", nonce);
context.Response.Headers.Add("Content-Security-Policy", string.Format(
"default-src 'none'; " +
"script-src 'self' 'unsafe-eval' 'nonce-{0}'; " +
"style-src 'self'; " +
"img-src 'self' data: https:; " +
"base-uri 'self'; " +
"upgrade-insecure-requests; " +
"object-src 'none'; ", nonce));
await next();
});
...
查看
...
@section Scripts {
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.min.js" nonce="@Context.Items["ScriptNonce"]"></script>
<script src="~/js/Views/Admin/users_index.min.js" nonce="@Context.Items["ScriptNonce"]"></script>
}
结果:
The Nonce is generated, it exists in HttpContext.Items, does not populate.
这看起来很简单,我真的很困惑为什么没有填充属性。 我对 Web 开发有点陌生,因此,如果您有什么特别之处,我们将不胜感激 ASP.Net Core 2 中的任何提示。
回答:First Comment; The nonce was there the entire time, chrome was hiding it.
【问题讨论】:
-
您是否正在查看 Chrome 开发者工具的元素选项卡中的
nonce属性?如果是这样,请查看从服务器返回的响应(在“网络”选项卡中)——您可能会感到惊讶。我刚刚尝试重现您的问题,发现一切正常,只是 Chrome 没有在 Elements 选项卡中显示 nonce 值(我相信这是一种安全措施)。 -
是的,这会导致问题吗?当我对值进行硬编码时,它会起作用。
-
我看到了,我不知道如何在 chrome 中显示它,但我在 fiddler 中打开它,果然,你的权利。它一直在那里。感谢您指出这一点,我绝不会猜到 chrome 会隐藏它。
标签: c# html razor asp.net-core