【问题标题】:Strict CSP: How to set nonce for styled components in next.js?严格的 CSP:如何在 next.js 中为样式化组件设置随机数?
【发布时间】:2019-10-15 09:44:20
【问题描述】:

所以,我尝试在我的 next.js 项目中使用 nounce 属性填充样式组件,但没有成功。正在设置 CSP 的 style-src,但由于未在样式中设置 nounce,因此会引发错误。我还需要做什么才能完成这项工作?

我目前的情况如下:

server.js

server.use((req, res, next) => {
  // nonce should be base64 encoded
  res.locals.styleNonce = Buffer.from(uuidv4()).toString('base64')
  next()
});

  server.use('*', (req, res, next) => {
    global.__webpack_nonce__ = res.locals.styleNonce;
    next()
  });

  server.use(helmet.contentSecurityPolicy({
      directives: {
          styleSrc: ["'self'", (req, res) => `'nonce-${res.locals.styleNonce}'`],
      }
  }));

_document.js

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage(App => props => sheet.collectStyles(<App {...props} />));
    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }
  render() {
    return (
      <Html lang="en">
        <Head>{this.props.styleTags}</Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

【问题讨论】:

  • 你让它工作了吗?
  • @TheLearner 不,很遗憾。
  • 也在为此苦苦挣扎,不知道除了完全删除我的 CSP 或替换样式组件之外还能做什么......

标签: javascript reactjs next.js


【解决方案1】:

document.js 中,虽然必须通过props 提供nonce,但Next.js 具有将nonce 应用于headbody 中所有加载的脚本/链接的功能 - 如果提供了它。

我面临的唯一主要问题是在组件级别的 next/head 内有条件地加载脚本,例如在接受 cookie 之后......事情变得更加复杂。

  render() {
    const { styleTags, language, nonce } = this.props;

    return (
      <html lang={language}>
        <Head {...{ nonce }}>
          {styleTags}
        </Head>
        <body>
          <Main />
          <NextScript {...{ nonce }} />
        </body>
      </html>
    );
  }

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-08-16
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多