提问人:Anup Shah 提问时间:2/4/2022 更新时间:5/14/2022 访问量:2855
使用 NWebSec 向 @Scripts.Render ASP.Net MVC 剃刀页面添加随机数值
Adding nonce value to @Scripts.Render ASP.Net MVC razor pages with NWebSec
问:
我正在尝试使用 NWebSec NuGet 包实现 Content-Security-Policy
基本配置级别目前正在工作,但尝试为项目中的每个脚本和样式添加随机数。
如何将随机数添加到下面的标签中以进行内联?
@Styles.Render("~/Content/css/file")
对于 BundleConfig,
bundles.Add(new ScriptBundle("~/Content/Scripts").Include(
"~/Content/Scripts/General.js"
));
我尝试使用一个新类,它正在工作,但是使用 NWebSec 包我无处可去。 以下是他们使用 @Html.CspScriptNonce() 指令的解决方案,这正在起作用。
<script @Html.CspScriptNonce()>document.write("Hello world")</script>
<style @Html.CspStyleNonce()>
h1 {
font-size: 10em;
}
</style>
答:
1赞
Steve Kerrick
3/3/2022
#1
与 ASP.Net MCV Bundle 一起使用时,您不能应用 Nonce,但幸运的是您不需要。NWebSec
不过,您可能需要更改一些东西。在该部分中,确保 对于 和 . 但是,是默认值,因此,如果任何其他声明都不需要这些元素,则可以省略它们。web.config
nwebsec > httpHeaderSecurityModule > securityHttpHeaders > content-Security-Policy
self="true"
style-src
script-src
self="true"
这是我的web.config中的部分。我同时使用样式和脚本包,并且没有第三方脚本。nwebsec
<nwebsec>
<httpHeaderSecurityModule xmlns="http://nwebsec.com/HttpHeaderSecurityModuleConfig.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="NWebsecConfig/HttpHeaderSecurityModuleConfig.xsd">
<securityHttpHeaders>
<content-Security-Policy enabled="true">
<default-src self="true" />
<font-src self="true">
<add source="https://fonts.gstatic.com" />
</font-src>
<object-src none="true" />
<style-src self="true">
<add source="https://fonts.googleapis.com" />
</style-src>
<base-uri none="true" />
</content-Security-Policy>
</securityHttpHeaders>
</httpHeaderSecurityModule>
</nwebsec>
评论
0赞
Anup Shah
3/3/2022
谢谢,史蒂夫,但根据你的代码,如果你使用内联脚本或样式,它仍然是一个安全问题,可能是可注入的。为了防止想要使用随机数
3赞
Alfredo Rojas Cuevas
5/14/2022
#2
我尝试的解决方案是按以下方式使用:@Styles.RenderFormat
@Styles.RenderFormat("<link href=\"{0}\" rel=\"stylesheet\" " + @Html.CspStyleNonce() +"/>","~/Content/css/file")
评论