gpt4 book ai didi

webforms - 如何使用 CSP(内容安全策略)将 WebForms 项目中动态创建的脚本列入白名单?

转载 作者:行者123 更新时间:2023-12-03 17:31:01 27 4
gpt4 key购买 nike

是否有使用 CSP(内容安全策略)将 WebForms 项目中动态创建的脚本列入白名单的安全方法?

使用 unsafe-inline像下面它的工作原理,但不推荐。

context.Response.Headers.Append("Content-Security-Policy", string.Format("default-src 'none'; connect-src 'self'; font-src 'self'; img-src 'self' data: https:; style-src 'self'; script-src 'self' 'unsafe-inline'"));

对于任何其他选项,例如 nonce-(random) ,我们看到此 CSP 错误消息:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash, or a nonce is required to enable inline execution.



enter image description here

最佳答案

动态脚本没有“安全内联”这样的东西,请尝试使用动态导入? (您可以在代码中重新加载此类脚本)。

您通常不必使用“不安全内联”,经常会出现问题的两件事是开发中的实时重新加载和代码中的 setTimeout/setInterval,它们可以轻松触发 CSP。所以最好在开发中禁用 CSP 以提高交付速度。 'unsafe-inline' 用于启用动态创建的脚本的执行。

更新

要解决此问题,您需要使用标准(可能使用 async/defer)加载自定义脚本 <script src="/myscript.js"></script>并且“不安全内联”要求消失了。但是,您的技术选择(“网络表单”)可能会限制您这样做的选择。无论如何要进行测试,请使用 cdn url 或单独的服务器(内部或外部)来交付您的脚本。我已经用 nodejs 在本地测试了这个,它按预期工作。您遇到的“问题”很可能是因为您编写了这样的代码(或代码放在那里):
<script>function unsafeInline() { ... }</script>
Modernizr 现在是 v3.6.0,您使用 v2.8.3 并消除错误,您可以将其添加到标题中:

<header>
<title>CSP Test</title>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com/;">
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
</header>

来自 related SO question :

If modernizr is injecting all that inline stuff than it seems like your choices are to either (a) add all those hashes, (b) use 'unsafe-inline' (but which basically defeats the whole purpose of CSP…), or (c) don’t use modernizr.



该问题的答案是:从 Modernizr 中删除“内联内容”。您可以随时使用 document.body.style = "background: #000000;";从外部库设置样式(或其他)属性。我在导入的外部脚本中尝试了所有“正常”代码事件,但它不会触发 CSP。通常我也指将对象(函数)分配给 window 对象并执行它们。

寻找 *.createElement("script") 或类似的,因为这肯定会触发 CSP。

关于webforms - 如何使用 CSP(内容安全策略)将 WebForms 项目中动态创建的脚本列入白名单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54095422/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com