j r*_*roc 1 security https http node.js express
我正在尝试在我的项目中使用内联脚本,但我不断收到此错误:“拒绝执行内联脚本,因为它违反了以下内容安全策略指令:“script-src 'self'”。'unsafe-inline' 关键字、哈希值 ('sha256-hyQXPyDjuL7UGCz8hPIbJ2ZzKwE8uqNzvUJB9/9T6jc=') 或随机数 ('nonce-...') 都需要启用内联执行。
我在这里查看了一堆其他类似的问题,他们都说这与元标记有关并包含以下内容:
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />
但这并没有什么区别,我已经从我的中删除了所有元标记<head> ,但仍然出现相同的错误。这个问题可能来自
<head> 哪里?我用 express-generator 创建了我的项目,但我在我的任何文件中都找不到任何 CSP。
我完全不知道是什么阻止了内联脚本,如果我能提供任何代码,请告诉我,但我不知道是什么原因造成的,我不知道要提供什么代码
Pet*_*jda 10
CSP 指令不是在元标记中设置,而是在 HTTP 标头中设置。
因为您用node.js和标记了问题express,这是在 express 中设置 CSP 标头的示例:
const express = require("express");
const app = express();
const port = 8080;
app.get("/", (req, res) => {
res
.set("Content-Security-Policy", "default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'")
.send("<html><head></head><body></body></html>");
})
app.listen(port, () => {
console.log("Listening on port %s", port);
});
Run Code Online (Sandbox Code Playgroud)
然后你可以在响应头中看到 CSP:
curl -v http://localhost:8080
* Rebuilt URL to: http://localhost:8080/
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.53.1
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Security-Policy: default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'
< Content-Type: text/html; charset=utf-8
< Content-Length: 39
< ETag: W/"27-ghawzGh2y9RPAcFY59/zgzzszUE"
< Date: Tue, 17 Nov 2020 00:01:04 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
<
* Connection #0 to host localhost left intact
<html><head></head><body></body></html>
Run Code Online (Sandbox Code Playgroud)