0

我很难找到我的问题的答案,毫无疑问,因为我不知道要搜索什么,但我希望这里的人可以提供帮助:)

我在托管反应应用程序的节点应用程序中使用随机数实现了头盔。

节点应用中的头盔实现:

app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
  next();
});

app.use(
  helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
      styleSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
    },
  })
);

在我的整个 react 应用程序中,我导入脚本和样式表的唯一位置是我的 index.html 页面的头部。所以我的问题是,我需要在下面的脚本和链接标签中添加什么才能正确使用带有 nonce 的 CSP?

反应应用程序 index.html

<!DOCTYPE html>

<html lang="en">
  <head>      

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link 
      rel="stylesheet" 
      href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
      nonce="What to put here, if it even goes here?"
    />
    
    <script 
      type="text/javascript" 
      src="https://code.jquery.com/jquery.min.js" 
      nonce="How do I implement the res.locals.cspNonce here?"
    >
    </script>

    
    <title>Some title</title>

4

3 回答 3

1

nonce 应该通过模板注入,以便在访问路由时始终生成的 nonce 始终是最新的。

于 2021-11-30T15:01:04.477 回答
1

React 应用程序大多是 SPA,其中页面的内容并未完全从服务器重新加载,而是通过 XMLHttpRequest() 部分刷新。

因此,在页面的部分“重新加载”时刷新“nonce”的值在技术上是不可能的,因为页面以这种方式“刷新”时无法更改部分中<meta http-equiv='Content-Security-Pilicy'...>的值。 由于这个原因,React 使用而不是 nonces。<head>
'hash-values'

'nonce-value'In React 应用程序只能在整个页面使用Server -Side Rendering时使用,它有很多陷阱并且很少使用。而在这种情况下,应用程序将失去 React 的所有好处。

于 2021-11-30T16:49:21.897 回答
-1

头盔维护者在这里。

您应该设置and标签的nonce属性。例如,如果生成的是,您将执行以下操作:<link><script>nonceabc123def456

<script nonce="abc123def456" src="https://example.com/script.js"></script>

因为 nonce 只能一次性使用,所以不能将 nonce 与静态 HTML 一起使用。换句话说,您需要服务器端的 HTML 渲染才能使用 CSP 随机数。

如果这对您来说是个问题,那么您不必使用随机数。可能有其他方法可以解决该问题,例如使用CSP 哈希代替脚本。

于 2021-12-01T15:20:33.803 回答