我正在尝试用NWebSec NuGet包实现内容安全策略。
基本的配置级别目前正在工作,但是尝试为项目中的每个脚本和样式添加nonce。
如何在下面的标签中添加一个nonce作为内联标记?
@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>发布于 2022-03-02 22:59:33
当将NWebSec与ASP.Net MCV一起使用时,不能将其应用于Nonce,但幸运的是,您不需要这样做。
不过,您可能需要在web.config中更改一些内容。在nwebsec > httpHeaderSecurityModule > securityHttpHeaders > content-Security-Policy部分中,确保style-src和script-src都是self="true"。但是,self="true"是默认的,所以如果您不需要任何其他声明都需要这些元素,就可以省略它们。
这是我web.config中的web.config部分。我同时使用样式和脚本包,而且没有第三方脚本。
<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>发布于 2022-05-13 18:57:13
我尝试的解决方案是以以下方式使用@Styles.RenderFormat:
@Styles.RenderFormat("<link href=\"{0}\" rel=\"stylesheet\" " + @Html.CspStyleNonce() +"/>","~/Content/css/file")https://stackoverflow.com/questions/70985220
复制相似问题