NET Core 3.1 MVC 在html中引用js的方法使用时不生效异常

  • 在html的select元素添加了onchange事件,changeContent方法也在当前html下。
<select id="changeLanguage" class="form-control  input-lg" asp-for="language" asp-items="Model.supportedLanguages" onchange="changeContent()"></select>
<script >
    function changeContent() {
        ......
    }
</script>

  • 运行起来后,选择变更后缺没有反应。

  • 后来找了很久,发现方法根本没有执行,然后在console也发现一句话(如下),因为CSP安全策略挡住了,发现项目代码中的过滤器确实添加了此策略(如下)
  Refused to execute inline event handler because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
var csp = "default-src 'self'; object-src 'none'; frame-ancestors https://*.XXXX.com; sandbox allow-forms allow-same-origin allow-scripts; base-uri 'self';";
if (!context.HttpContext.Response.Headers.ContainsKey("Content-Security-Policy"))
{
    context.HttpContext.Response.Headers.Add("Content-Security-Policy", csp);
}

后来查找相关资料,及console的提示,需要在csp上添加script-src 'self' unsafe-inline;,但显然这不符合安全规范。
我目前做法是在script添加nonce属性,随机输入一串字符,同时也在csp上添加script-src 'self' 'nonce-2726c7f26cfgfgsedd435877d7d8i38dx87bmw7r0hms645kbchr873k';
但显然固定的字符串,并不安全,应采取随机hash作为值。(后续再研究)

<script nonce="2726c7f26cfgfgsedd435877d7d8i38dx87bmw7r0hms645kbchr873k">
......
</script>
posted @ 2023-12-06 09:16  Cody&  阅读(93)  评论(0编辑  收藏  举报