使用 ASP.NET MVC Kendo 组件时如何避免 Telerik KendoUI 创建内联脚本?
避免内联脚本的原因是遵守 CSP header
Content-Security-Policy: script-src 'self' 'unsafe-eval' https://kendo.cdn.telerik.com
并且不要出现类似的错误
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' https://kendo.cdn.telerik.com".
有没有办法删除剑道生成的内联脚本或 将内容安全策略随机数/sha256附加到脚本中?
简单示例(KendoUI 菜单)
cshtml
@(Html.Kendo().Menu()
.Name("nav-menu")
.Items(items =>
{
items.Add().Text("Home").Action("Index", "Overview");
})
)
浏览器 html
<ul class="k-widget k-reset k-header k-menu k-menu-horizontal" id="nav-menu" data-role="menu" tabindex="0" role="menubar" aria-activedescendant="nav-menu_mn_active">
<li class="k-item k-state-highlight k-state-default k-first" role="menuitem">
<a class="k-link" href="/">Home</a>
</li>
</ul>
<script>
jQuery(function(){jQuery("#nav-menu").kendoMenu({});});
</script>
<小时/>
解决方案
在 @dimodi 回答之后,我最终在 kendo 延迟初始化脚本上使用了 nonce。
cshtml
@(Html.Kendo().Menu()
.Name("nav-menu")
.Items(items =>
{
items.Add().Text("Home").Action("Index", "Overview");
})
.Deferred()
)
<script type="text/javascript" nonce="@Html.ScriptNonce()">
@Html.Kendo().DeferredScripts(false)
</script>
Startup.cs
public partial class Startup
{
public void Configuration(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[] {$"script-src 'self' 'unsafe-eval' https://kendo.cdn.telerik.com 'nonce-{nonce}';"
});
return next();
});
}
}
public static class NonceHelper
{
public static IHtmlString ScriptNonce(this HtmlHelper helper)
{
var owinContext = helper.ViewContext.HttpContext.GetOwinContext();
return new HtmlString(owinContext.Get<string>("ScriptNonce"));
}
}
最佳答案
您可以控制 Kendo UI MVC 内联脚本在页面上的呈现位置,但无法完全删除它们。实际上,您可以,但是小部件将不会初始化。
考虑使用非 MVC Kendo UI 小部件:
http://docs.telerik.com/kendo-ui/aspnet-mvc/kendo-ui-vs-mvc-wrappers
Vanilla HTML/JavaScript Kendo UI widgets provide full control over the placement of the initialization scripts - server wrappers render the widgets' initialization scripts right after the widget's HTML output. Even if you use deferred initialization, the scripts are still kept in the View. When using plain (non-wrapper) Kendo UI widgets, you write the initialization scripts yourself and can move them to external script files.
还要记住,Kendo UI 模板依赖于 eval
,如果启用 CSP,这也会带来麻烦。
关于javascript - 如何让 KendoUI MVC 与内容安全策略配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39125743/