【问题标题】:CSP block Google Tag Manager in NextJs still using nonceCSP 在 NextJs 中阻止 Google Tag Manager 仍然使用 nonce
【发布时间】:2022-01-04 22:15:38
【问题描述】:

我在我的项目中使用谷歌标签管理器,但是当我添加 CSP 时,它会阻止 GTM。

CSP:

default-src https: http: 'strict-dynamic' 'nonce-{NONCE-KEY}' 'unsafe-inline' 'self' https://www.googletagmanager.com;

代码:

<Html lang='es'>
    <Head nonce='{NONCE-KEY}'>
        <script
            nonce='{NONCE-KEY}'
            aria-hidden='true'
            dangerouslySetInnerHTML={{
                            __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                'https://www.googletagmanager.com/gtm.js?id='+i+dl;var n=d.querySelector('[nonce]');
                n&&j.setAttribute('nonce',n.nonce||n.getAttribute('nonce'));f.parentNode.insertBefore(j,f);
                })(window,document,'script','dataLayer','${GTM_ID}');`,
                        }}
        />
    </Head>
    <body aria-label='Cargando'>
        <noscript                  
            aria-hidden='true'
            dangerouslySetInnerHTML={{
                            __html: `<iframe  src="https://www.googletagmanager.com/ns.html?id=${GTM_ID}" height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
                        }}
        />
        <Main />
        <div id='tooltip' />
        <NextScript nonce='{NONCE-KEY}' />
    </body>               
</Html>

错误:

根据文档,仅添加 nonce 应该可以工作,因为出于安全原因,我不想将“unsafe-eval”指令添加到我的 CSP。

【问题讨论】:

    标签: reactjs next.js content-security-policy nonce


    【解决方案1】:
    1. 从您的错误消息中不清楚它是由 GTM 还是其他脚本引起的。但是,只有在“自定义 HTML 标记”中使用自定义 JavaScript 变量名称时,GTM 才需要 'unsafe-eval'

      要摆脱 'unsafe-eval',您可以使用 custom templates 而不是自定义 JavaScript 变量名称。

    2. 切勿使用基于default-src 指令的严格内容安全策略,因为它会导致fatal security consequences in Firefox

    【讨论】:

    • 非常感谢,崩溃消息是由 GTM 引起的,因为我使用的是自定义 Javascript 变量,所以我对数据层变量进行了更改,并从我的应用程序中通过 push 方法发送了这些值。我还改进了策略,考虑到避免使用 default-src。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多