6

I'm struggling with serving a build created with "create-react-app" using Express with Helmet. I'm getting several errors in the explorer console related to Content Security Policy:

csp-errors

Of course, it isn't showing the app. I noticed that if a remove Helmet as middleware in Express it works but that's not the solution I want. This is my server code:

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const bodyParser = require('body-parser');

/**
 * Server Configuration
 */

const whitelist = [];

const app = express();

// Express Configurations

// Enable reverse proxy support in Express. This causes the the "X-Forwarded-Proto" header field to be trusted so its
// value can be used to determine the protocol. See // http://expressjs.com/api#app-settings for more details.

app.enable('trust proxy');

app.use(morgan('dev')); // Log every request to the console
app.use(helmet()); // Configure secure Headers
app.use(bodyParser.urlencoded({ extended: false })); // Enable parsing of http request body
app.use(bodyParser.json());

// CORS Configuration

const corsOptions = {
  origin: (origin, callback) => {

    if (whitelist.indexOf(origin) !== -1 || !origin) {

      callback(null, true);

    } else {

      callback(new Error('Not allowed by CORS'));

    }

  },
};

app.use(cors(corsOptions)); // Allow CORS

/**
 * Launcher method
 */

app.start = () => {

  // start node server
  const port = process.env.PORT || 3000;
  app.listen(port, () => {

    console.log(`App UI available http://localhost:${port}`);
    console.log(
      `Swagger UI available http://localhost:${port}/swagger/api-docs`,
    );

  });

};

/**
 * App Initialization
 */

function initializeApp(readyCallback) {

  readyCallback(null, app);

}

module.exports = (readyCallback) => {

  initializeApp(readyCallback);

};

Can anyone give me a hand? Thanks in advance!

4

3 回答 3

18

头盔维护者在这里。

之所以会发生这种情况,是因为 Helmet 默认设置的内容安全策略。要解决您的问题,您需要配置 Helmet 的 CSP。

MDN 有一个很好的关于 CSP 的文档,我建议您阅读作为背景知识。之后,查看Helmet 的 README以了解如何配置其 CSP 组件。

为了针对这个问题提供一些帮助,让我们看一下您看到的一个错误:

Content Security Policy: This page's settings blocked the loading of a resource at inline ("script-src").

这个错误告诉你script-src你的 CSP 的指令不允许内联 JavaScript,所以它被阻止了。

这被认为是“内联”JavaScript:

<script>console.log('hello world!')</script>

然而,这不是:

<script src="/foo.js"></script>

有几种方法可以解决这个问题:

  1. 将哈希或随机数添加到内联<script>并在您的 CSP 中使用。请参阅MDN 上的此示例以获取帮助。

  2. 重构您的应用程序以完全避免内联脚本。

  3. 更新您的 CSP 以允许不安全的内联脚本。你会做这样的事情:

    app.use(
      helmet({
        contentSecurityPolicy: {
          directives: {
            ...helmet.contentSecurityPolicy.getDefaultDirectives(),
            "script-src": ["'self'", "'unsafe-inline'", "example.com"],
          },
        },
      })
    );
    

    请注意,这被认为是不安全的。

  4. 禁用 CSP。这是最危险的选择,所以我不推荐它。

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

您的其他错误,例如fonts.googleapis.com错误,请参阅default-src,如果未指定指令,这是后备。

总之:要解决您的问题,您需要告诉 Helmet 配置您的 CSP。

于 2020-11-07T15:45:22.507 回答
6

带着同样的问题通过谷歌来到这里。我不想降低头盔中的任何安全设置,所以我更改了我的 react 构建配置。只需添加行

INLINE_RUNTIME_CHUNK=false

到react 应用根目录中的.env。然后,当您运行 npm run build构建应用程序时,所有内联脚本都将被删除,并且不再违反 CSP。这确实在首次加载站点时添加了一个额外的初始 HTTP GET 请求,但在我看来似乎值得安全收益。

于 2020-12-29T06:10:46.643 回答
0

这是第三种解决方案。将 package.json 中的构建脚本更改为以下内容:

"build": "GENERATE_SOURCEMAP=false node scripts/build.js"

于 2021-03-23T03:39:34.653 回答