无法从HttpContext.Items

时间:2018-09-25 17:02:48

标签: c# html razor asp.net-core

我的问题似乎很简单,我觉得我遗漏了一些非常明显的东西;但是我无法确定为什么脚本元素上的Nonce属性没有填充,而是保留了空字符串。

我决定使用HttpContext内部的Items集合存储随机数,因为据我所知,它是每个请求的。

Startup.Configure(IApplicationBuilder应用程序,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.

1 个答案:

答案 0 :(得分:0)