首页 > 解决方案 > 使用 Cloudflare 的 Express.js 头盔 CSP 设置 - 放入什么?

问题描述

我在 Heroku(免费层)上部署了一个简单的投资组合网站。该站点使用 Express Node.js 和 React 作为前端构建。为了使用需要 SSL 的 .dev 域,我注册了 Cloudflare。现在一切正常,除了我的发送电子邮件表格。我收到以下错误:

Refused to connect to `https://<my-app>.herokuapp.com/api/v1/email/sendemail' because it violates the following Contect Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

我发现它与头盔和 CSP 政策有关,但我不明白我到底需要在那里放什么。作为临时解决方案,我像这样禁用了 CSP:

app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

但理想情况下,我想做这样的事情:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        ...helmet.contentSecurityPolicy.getDefaultDirectives(),
        'connect-src': ["'self'", 'cdnjs.cloudflare.com'],
      },
    },
  })
);

但我不知道在里面放什么。cdnjs.cloudflare.com 和 ajax.cloudflare.com 都不起作用。

标签: expressherokucloudflarehelmet.js

解决方案


以下是 Express 中 CSP 的最常见用法。这是我的应用程序的配置,我认为您应该在那里找到所需的一切:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        blockAllMixedContent: [],
        fontSrc: ["'self'", 'https:', 'data:'],
        frameAncestors: ["'self'", 'https://accounts.google.com/'],
        frameSrc: ["'self'", 'https://accounts.google.com/'],
        imgSrc: ["'self'", 'data:'],
        objectSrc: ["'self'", 'blob:'],
        mediaSrc: ["'self'", 'blob:', 'data:'],
        scriptSrc: ["'self'", 'https://apis.google.com'],
        scriptSrcAttr: ["'none'"],
        styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
        upgradeInsecureRequests: [],
        connectSrc: ["'self'", 'https://my-app.herokuapp.com'],
      },
    },
  })
);

connectSrc应该包括https://my-app.herokuapp.com,就像您在最后一行看到的那样。


推荐阅读