无法使用 next.config.js 和中间件.ts 在 NextJS V13.4.12 中为 GTM 脚本设置内容安全策略

Unable to set up Content Security Policy for GTM script in NextJS V13.4.12 using next.config.js and middleware.ts

提问人:Dibyendu Saha 提问时间:10/28/2023 最后编辑:Dibyendu Saha 更新时间:10/30/2023 访问量:29

问:

在 NextJS V13.4.12 中设置内容安全策略时出错。

创建middleware.ts如下:

import { NextRequest, NextResponse } from 'next/server';

export const middleware = (request: NextRequest) => {
  const nonce = 'RklMTFDSWlWRVIUYTRTRQo=';
  const cspHeader = `
    default-src 'self';
    script-src 'self' 'nonce-${nonce}' 'strict-dynamic' 'unsafe-inline';
    style-src 'self' 'nonce-${nonce}' 'unsafe-inline';
    connect-src 'self' 'nonce-${nonce}';
    img-src 'self' blob: data:;
    font-src 'self';
    object-src 'none';
    base-uri 'self';
    form-action 'self';
    frame-ancestors 'none';
    block-all-mixed-content;
    upgrade-insecure-requests;
`;

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-nonce', nonce);
  requestHeaders.set(
    'Content-Security-Policy',
    cspHeader.replace(/\s{2,}/g, ' ').trim()
  );

  return NextResponse.next({
    headers: requestHeaders,
    request: {
      headers: requestHeaders,
    },
  });
};

export const config = {
  matcher: [
    {
      source: '/((?!api|_next/static|_next/image|favicon.ico).*)',
      missing: [
        { type: 'header', key: 'next-router-prefetch' },
        { type: 'header', key: 'purpose', value: 'prefetch' },
      ],
    },
  ],
};

在控制台中出现错误:

Refused to load the script 'https://www.googletagmanager.com/gtag/js?id=G-64952CCZ8D' because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-RklMTFDSWlWRVIUYTRTRQo=' 'strict-dynamic' 'unsafe-inline'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' 'nonce-RklMTUlWRVJTRQo=' 'unsafe-inline'". Note that 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list.

将随机数添加到 NextJS Script 标记:

<Script nonce='RklMTFDSWlWRVIUYTRTRQo=' src=https://www.googletagmanager.com/gtag/jsid=G-64952CCZ8D />

如果您需要任何其他详细信息,请告诉我。

reactjs google-tag-manager xss next.js13

评论


答: 暂无答案