Helmet JS CSP 配置允许外部 css 和 JS 脚本 - 内联脚本在哪里?

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

我对 JavaScript 和 ExpressJS 比较陌生。我正在尝试制作一个具有功能登录页面的网络应用程序。我正在尝试配置头盔 JS 中间件以允许外部 CSS 和脚本。但是我仍然收到:

Content-Security-Policy: The page’s settings blocked an inline script (script-src-elem) from being executed because it violates the following directive: “script-src 'self'”
.

我不确定内联脚本位于我的 html 文件中的位置。

这是我的文件夹结构:

-> public
    -> Login_Page_template
        - logo.jpg
        - login_page_client.js
        - static_login_page.html
        - static_login_styles.css
-> src
    -> routes
        - LOGIN_PAGE.js

- Entry_Point.js

哪里

Entry_Point.js
是:

// Date Created: September 11 2024
// Date Last Updated: September 23 2024 

const express = require("express");
const ejs = require("ejs");
const cors = require("cors");
const fs = require("fs");
const https = require("https");
const helmet = require("helmet");

// Importing Routes
const getItems = require("./src/routes/DB_GET_ITEMS");
const login_page = require("./src/routes/LOGIN_PAGE");

const app = express();
// View engine setup 
app.set('view engine', 'ejs');

// Allows request from any IP (prevent any CORS error)
app.use(cors()); 

app.use(express.json({limit: "1mb"}));

// Enable parsing of URL-encoded data on all routes:
app.use(express.urlencoded({
   extended: true, // Whether to use algorithm that can handle non-flat data strutures
}));

// Define the Content Security Policy (from chatgpt)
const cspConfig = {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: [
        "'self'",         // Allows styles from your own domain
        'https://fonts.googleapis.com' // Allow Google Fonts, etc.
      ],
      scriptSrc: ["'self'"],
      fontSrc: [
        "'self'",
        'https://fonts.gstatic.com' // Allow fonts from Google Fonts
      ],
    },
  };
  

// added helmet as middleware
app.use(helmet({
    contentSecurityPolicy:true,
    directives: cspConfig.directives,
})); 

app.get("/",login_page.Send_login_page);
app.get("/params/",getItems.Router_DB_Params);

// made some self signed keys - not CA (not authorized by acceptable vendor)
const options = {
    key: fs.readFileSync(__dirname+"\\config\\cert\\key.pem"),
    cert: fs.readFileSync(__dirname+"\\config\\cert\\cert.pem")
};

https.createServer(options, app).listen(80, ()=>{
    console.log("https://localhost:80/");
});

LOGIN_PAGE.js
是:

// Date Created: September 16 2024
// Date Last Updated: September 24 2024

const express = require("express");
const app = express();
const path = require('path');
const cors = require('cors');

app.use(cors()); // Allows request from any IP (prevent any CORS error)
app.use(express.static(path.join(__dirname, '../../public'))); // used to make it easier to reference static files such as certain .css and .html files

// Enable parsing of URL-encoded data on all routes:
app.use(express.urlencoded({
    extended: false, // Whether to use algorithm that can handle non-flat data strutures
 }));

function Send_login_page(req,res,next){
    const options = {root: path.join(__dirname,"../../public/")};
    res.sendFile("/Login_Page_template/static_login_page.html",options);
};

module.exports= {
    Send_login_page,
};

static_login_page.html
是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Portal</title>
    <link rel="stylesheet" src="./static_login_styles.css">

</head>
<body>    
    <div class="container">
        <div class="logo">
            <img src='./logo.jpg/' alt="Logo">
        </div>
        <div class="form">
            <form>
                <h1>Sign In?</h1>

                <input type="text"  id="username"  placeholder="Username" name="username">
                
                <input type="text"  id="password"  placeholder="Password" name="password">
                
                <input type="submit"  id="Submit_Login_btn"  value="Login">
            </form>
        </div>
        <div class="bypass">
            <a href="https://192.168.10.57:80/params/">
                <input type="button" name="Button" value="View">
            </a>
        </div>
    </div>
    <script type="text/script" src='./login_page_client.js'></script>
</body>
</html>

最后

login_page_client.js
是:

// Date Created: July 23 2024
// Date Last Updated: August 26 2024

const login_form = document.querySelector('form');

login_form.addEventListener("submit", e => {
  e.preventDefault();

  var button = document.getElementById("Submit_Login_btn");
  var username_input = document.getElementById("username");
  var password_input = document.getElementById("password");

  const form_data = new FormData(login_form);

  const urlEncoded = new URLSearchParams(form_data).toString();
  
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: urlEncoded
  };

  const response = fetch('/api/login-details',options);

  
});

请注意,当我使用 Fire Fox 的附加样式表选项附加样式时,样式会正常加载,不会出现错误。

javascript express helmet.js
1个回答
0
投票

这里是头盔维护员。这看起来像是您问题的一部分:

app.use(helmet({
    contentSecurityPolicy:true,
    directives: cspConfig.directives,
}));

它应该看起来像这样:

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

如果您从某处加载脚本或使用内联脚本,则需要更改 CSP 指令以适应这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.