Next.js 中的内容安全策略 (CSP) - 如何将其传递到完整应用程序?

问题描述 投票:0回答:1

我在项目中使用 Next.js 和单独的 Express 后端,并希望实施内容安全策略 (CSP),并使用随机数,因为我知道这是最佳实践。

根据next.js文档,我根据此链接创建了一个middleware.js文件:https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy

到目前为止,一切都很好。

但是,我现在想在应用程序中适用于所有脚本的某个位置访问此“随机数”。我的想法是在 _document 中访问它,并将随机数传递给 NextScript。我一直在尝试访问 _document 文件中的标头,但我的测试方法都不起作用(getServerSideProps/getStaticProps)。我如何获得这个随机数?将其添加到 中就足够了吗?

我的_文档看起来像这样


// Approach 1 which does not work
// import { headers } from "next/headers";
// Approach 1 which does not work

export default function Document() {

  // Approach 1 which does not work
  // const nonce = headers().get("x-nonce");
  // console.log(nonce);
  // Approach 1 which does not work

  return (
    <Html>
      <Head>
        <link
          href="https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap"
          rel="stylesheet"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

// example 2, running getSeriverside props - it seems it does not happen?
export async function getServerSideProps({ req }) {
  try {
    console.log(req);
    // this is not logging anywhere...

    return {
      props: { connect: "example fuccess" },
    };
  } catch (err) {
    return {
      props: { connect: "example fail" },
    };
  }
}

// example 3, running getStaticProps - also does not fire
export async function getStaticProps({ req }) {
  try {
    console.log(req);
    // this is not logging anywhere...

    return {
      props: { connect: "example fuccess" },
    };
  } catch (err) {
    return {
      props: { connect: "example fail" },
    };
  }
}
node.js reactjs next.js content-security-policy
1个回答
0
投票

我没有关于如何访问中间件中生成的随机数的答案,但您可以生成整个 CSP,包括

_document.tsx
中的随机数,然后将其放入
<meta httpEquiv="Content-Security-Policy" content={csp} />
中。您将无法使用标题中可以使用的某些功能(查看更多),但只要但如果您不需要,并确保上面没有任何脚本或其他内容那个元标记,它的行为应该像标题一样。

© www.soinside.com 2019 - 2024. All rights reserved.