头盔 csp 未出现在浏览器中

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

我正在尝试向我的应用程序添加内容安全策略。所以我使用头盔csp。但是当我添加它并在浏览器/终端中检查它时,我发现内容安全策略没有设置。不明白为什么?

我有一个像这样的 prod.js 模块

const helmet = require('helmet');
const compression = require('compression');
const crypto = require("crypto");

module.exports = function (app) {

app.use(helmet())

    app.use((req, res, next) => {
        res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
        next();
      });
      
      app.use((req, res, next) => {
        csp({
          useDefaults: true,
          directives: {
             scriptSrc: [ "'self', js.stripe.com', 'https://checkout.stripe.com', 
             'js.stripe.com',  'https://billing.stripe.com'"],  
             'https://www.googletagmanager.com', 
             '*.googletagmanager.com',( request, response ) => `'nonce-${res.locals.cspNonce}'` ],
            styleSrc:  ["'unsafe-inline'"],
            connectSrc:[" * 'self' https://checkout.stripe.com https://billing.stripe.com"],
            frameSrc:  [" 'self  https://checkout.stripe.com  https://billing.stripe.com https://js.stripe.com "],
            imgSrc:    [" 'self' blob: https://api.wcompany.com/  data:"], 
          },
        })(req, res, next);
    });




    app.use(compression());
};

然后我有这样的index.js 文件:

const winston = require('winston');
const express = require('express');
const https = require('https');
const path = require('path');
const fs = require('fs');
const app = express();


require('./startup/routes')(app);
require('./startup/db')();
require('./startup/config')();
require('./startup/validation')();
require('./startup/prod')(app);

const port = process.env.PORT || 3000;




但我在浏览器中看不到内容策略标头。我是否应该显式添加 res.headers 以在浏览器中查看 CSP。


Also on terminal I checked curl http://localhost:3000 --include

Access-Control-Allow-Origin: *
Content-Security-Policy: default-src 'none'
X-DNS-Prefetch-Control: off
Expect-CT: max-age=0
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Download-Options: noopen
X-Content-Type-Options: nosniff
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: no-referrer
X-XSS-Protection: 0
Content-Type: text/html; charset=utf-8
Content-Length: 139
Vary: Accept-Encoding
Date: Fri, 25 Feb 2022 15:57:17 GMT
Connection: keep-alive
Keep-Alive: timeout=5

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /</pre>
</body>
</html>




P.S:我对编程还很陌生。非常感谢任何帮助。

node.js express
2个回答
0
投票

您没有将

helmet
加载到您的
express
应用程序中。您需要添加这样的内容:

app.use(helmet())

0
投票

我知道这有点晚了,也许你已经明白了,但是你的

( request, response ) => `'nonce-${res.locals.cspNonce}'`

不正确。您应该重命名参数或像这样引用它们的正确名称

( request, response ) => `'nonce-${response.locals.cspNonce}'`

( req, res) => `'nonce-${res.locals.cspNonce}'`
© www.soinside.com 2019 - 2024. All rights reserved.