【问题标题】:Html Attribute not populating from HttpContext.Items未从 HttpContext.Items 填充 Html 属性
【发布时间】: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


【解决方案1】:
【解决方案2】:

正如其他人所说,出于安全原因,Chrome 只是从调试窗口中删除随机数。

但是,除非您使用 JS 代码创建内联脚本,否则您不需要在脚本上使用 nonce,这些脚本是静态文件并由文件系统提供服务(即浏览器将单独请求)。 nonce 仅用于内联脚本,以证明它们是由服务器('self')设计的。

样式也是如此。

您还应该在创建 nonce 时删除“unsafe-eval”。 unsafe-eval 将意味着 nonce 毫无意义。

例如

"script-src 'self' 'nonce-{0}';

@section Scripts {
    <script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/js/Views/Admin/users_index.min.js"></script>
    <script nonce="@Context.Items["ScriptNonce"]">
       console.log('hello') 
    </script>
}

需要明确:一些库,如 jQuery 和 GTM 在头部创建内联脚本,这违反了 CSP,除非它们“通过”随机数到他们创建的内联脚本。

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 2010-12-20
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多