.Net Core 'asp-append-version' 干扰 Umbraco 9 中的 CSP 随机数

.Net Core 'asp-append-version' interfering with CSP nonces in Umbraco 9

我有一个非常简单的 TagHelper,它将当前的 CSP 随机数添加到指定的标签。

在我开始使用 asp-append-version 之前一切正常,此时浏览器开始抱怨脚本被阻止:

[仅报告] 拒绝加载脚本,因为它违反了以下内容安全策略指令:“script-src 'strict-dynamic' 'nonce-7TYX/FgHsrvHOORSEBRB3h0e'”。请注意 'strict-dynamic' 存在,因此基于主机的白名单被禁用。请注意,'script-src-elem' 未明确设置,因此 'script-src' 用作后备。

当我查看页面源代码时,我可以看到我的 nonce 已正确应用,但是我们最终得到 two src 属性,这对我来说似乎不正确:

<script src="/web/scripts/main.js?v=K0HDUmKd22yWAqRgrnhcGk69aHiFH8qUh2kPLDSbV0c" 
        src="/web/scripts/main.js" 
        nonce="GLBtUe54MABq4Ld2Wtznf8P2"></script>

这可能是问题所在吗?我看到两个属性,即使没有自定义标签助手(也尝试在系统中取消注册所有自定义标签助手,但我仍然面临这个问题)。

它甚至不能使用静态硬编码随机数(根本没有标签助手)。

示例脚本参考:

<script asp-append-version="true" asp-add-nonce="true" src="/web/scripts/main.js"></script>

TagHelper class:

[HtmlTargetElement("script", Attributes = "asp-add-nonce")]
public class NonceTagHelper : TagHelper
{
    private readonly ILogger<NonceTagHelper> logger;
    private readonly ICspNonceBuilder cspNonceBuilder;

    public NonceTagHelper(ILogger<NonceTagHelper> logger, ICspNonceBuilder cspNonceBuilder)
    {
        this.logger = logger;
        this.cspNonceBuilder = cspNonceBuilder;
    }

    [HtmlAttributeName("asp-add-nonce")]
    public bool AddNonce { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (!this.AddNonce)
        {
            return;
        }

        var nonce = this.cspNonceBuilder.GetRequestNonce();

        output.Attributes.SetAttribute("nonce", nonce);
    }
}

如果我删除 asp-append-version,这一切都会开始正常工作 - 输出:

<script nonce="GLBtUe54MABq4Ld2Wtznf8P2" type="module" src="/web/scripts/main.js"></script>

但如果可能的话,我想继续使用它。我错过了什么?我不确定它是自定义标签助手,因为没有它问题是可以重现的(硬编码随机数)。

我发现了问题。 Umbraco 9 包括一个捆绑和缩小包作为标准 https://github.com/Shazwazza/Smidge:

@addTagHelper *, Smidge
@inject Smidge.SmidgeHelper SmidgeHelper

Smidge 包括一些以 <script> 标签上的 src 属性为目标的标签助手。

似乎是在复制整个属性:

https://github.com/Shazwazza/Smidge/blob/master/src/Smidge/TagHelpers/SmidgeScriptTagHelper.cs#L48

// Pass through attribute that is also a well-known HTML attribute.
// this is required to make sure that other tag helpers executing against this element have
// the value copied across
if (Source != null)
{
     output.CopyHtmlAttribute("src", context);
}

从解决方案中删除它可以解决问题。

编辑* This has now been patched and will be releasing with version 4.1.0