HTTP协议特性之CSP 指令——NodeJs版

本文介绍了HTTP响应头Content-Security-Policy(CSP)及其在防止跨站脚本攻击中的作用。内容包括CSP的概念,常用的限制方式,并提供了一个NodeJs的快速入门案例,展示如何配置和测试CSP策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Content-Security-Policy——内容安全策略

HTTP 响应头 Content-Security-Policy 允许站点管理者在指定的页面控制用户代理的资源。除了少数例外,这条政策将极大地指定服务源 以及脚本端点。这将帮助防止跨站脚本攻击(Cross-Site Script) (XSS).

二、限制方式

Content-Security-Policy<policy-directive>; <policy-directive>

<policy-directive>常用指令

default-src:为其他指令提供备用服务
            default-src无法限制form表单的提交
            另需 form-action 'self' 来进行限制
connect-src:限制能通过脚本接口加载的URL。
font-src:限制通过@font-face加载的字体源。
frame-src: 限制通过类似<frame><iframe> 标签加载的内嵌内容源。
img-src: 限制图片和图标源
media-src:限制通过<audio><video> 标签加载的媒体文件源。
object-src:限制通过  <object>, <embed><applet> 标签加载源。
script-src:限制javascript 源。
style-src:限制层叠样式表文件源。

其他指令参考:Content-Security-Policy

三、快速入门案例

csp.js

const http = require("http")
const config = require("./config/config")
const fs = require("fs");
const server = http.createServer((requestMsg, response) => {
    if(requestMsg.url === "/") {
        fs.readFile("./test.js", (err, data) => {
            //问题:Chrome Content-type:"application/x-javascript——》document
            response.writeHead(200, "ok", {
                "Content-type": "application/x-javascript",
                "Content-Security-Policy": "script-src 'self';form-action 'self'"
            })
            response.end(data);
        })
    }else{ //
        response.writeHead(200,"ok",{
            "Content-type":"application/x-javascript"
        })
        response.end("console.log(123)");
    }
})

server.listen(config.port, config.host, () => {
    console.log(`server starting at ${config.host}:${config.port}`)

})

test.js

console.log('abc')

csp.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        img{
            width: 100px;
        }
    </style>
</head>
<body>
    <form action="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.min.js">
        <input type="submit" value="提交">
    </form>
    <img src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3012445745,1904104267&fm=27&gp=0.jpg" alt="">
</body>
<script>
    console.log("我是内联脚本");
</script>
<script src="/dhakdhaskj"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.min.js"></script>
</html>

测试结果:
这里写图片描述
点击提交后:
这里写图片描述
表示default-src无法限制form表单的提交

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值