为什么我收到 "Hello World" 的简单消息的内容安全策略报告?

Why do I receive a Content-Security-Policy report from a simple message of "Hello World"?

我想尝试一下 Content-Security-Policy。我创建了以下程序

这是我的代码:

#!/usr/bin/python
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Security-Policy-Report-Only", "default-src; report-uri /")
        self.end_headers()
        self.wfile.write(b'Hello, world!')

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(body)
        print(body)
        self.wfile.write(response.getvalue())

httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
print ("Serving on http://localhost:8000")
httpd.serve_forever()

我在浏览器中访问 http://localhost:8000,这是我得到的:

'{"csp-report":{"blocked-uri":"","document-uri":"http://localhost:8000/","line-number":1,"original-policy":"default-src \'none\'; report-uri http://localhost:8000/","referrer":"","script-sample":";(function installGlobalHook(window) {\n ...","source-file":"http://localhost:8000/","violated-directive":"default-src"}}'

这是什么?我在隐身模式下进行了尝试,以确保没有扩展名 运行。

default-src 是一个决定从哪里加载资源的指令。 Empty 默认为 'none',所以这就是响应中有 "violated-directive":"default-src" 的原因。您应该在 do_GET():

中将其更改为 'self'
self.send_header("Content-Security-Policy-Report-Only", "default-src 'self'; report-uri /")

Incognito 毕竟不会停止加载项。违规行为来自反应开发者工具。禁用它可以解决问题。