You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免本地jQuery文件违反script-src CSP指令?

问题:本地jQuery文件触发CSP内联脚本错误的排查与解决

背景

客户要求为软件添加script-src安全策略以符合其安全标准,已采用nonce方案配置相对安全的CSP策略,可正常运行大部分代码,但本地引入的jquery-3.5.1.min.js触发浏览器控制台错误:拒绝执行内联脚本,因违反以下Content Security Policy指令,无更多有效细节。已知jQuery官方论坛提及该问题在多个版本前已修复,目前不想改用远程URL引入jQuery,需在不降低代码安全性的前提下解决该错误,避免无法通过客户安全扫描。

当前CSP配置方案

Web.config配置

仅配置object-src规则:

<add name="Content-Security-Policy" value="object-src 'none';" />

Startup.cs中的Nonce生成与script-src配置

通过ConfigureNonce方法生成随机nonce并注入CSP的script-src规则:

private void ConfigureNonce(IAppBuilder app)
{
    app.Use((context, next) =>
    {
        var rng = new RNGCryptoServiceProvider();
        var nonceBytes = new byte[32];
        rng.GetBytes(nonceBytes);
        var nonce = Convert.ToBase64String(nonceBytes);
        context.Set("ScriptNonce", nonce);

        context.Response.Headers.Add("Content-Security-Policy",
            new[] { string.Format("script-src 'self' 'unsafe-eval' xxxxxx yyyyyy http://localhost:* 'nonce-{0}'", nonce) });
        return next();
    });
}

配置说明:

  • xxxxxx:项目依赖的第三方组件URL
  • yyyyyy:帮助文档的URL
  • 'unsafe-eval':因使用Kendo框架必须添加
  • http://localhost:*:仅开发环境用于解决Browser Link导致的script-src违规问题,生产环境会移除

Nonce辅助类(NonceHelper.cs)

用于在视图中获取生成的nonce值:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace dTIMSi.Helpers
{
    public static class NonceHelper
    {
        public static IHtmlString ScriptNonce(this HtmlHelper helper)
        {
            var owinContext = helper.ViewContext.HttpContext.GetOwinContext();

            return new HtmlString(owinContext.Get<string>("ScriptNonce"));
        }
    }
}

内联脚本的Nonce使用方式

为页面中的内联脚本添加nonce属性以通过CSP校验:

<script type="text/javascript" nonce="@Html.ScriptNonce()">
    // 内联脚本逻辑代码
</script>

核心疑问

当前配置逻辑清晰可行,已能解决大部分内联脚本的CSP校验问题,但本地引入的jQuery文件为何仍触发内联脚本错误?该如何解决?


内容的提问来源于stack exchange,提问作者ysi_d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:10:52