CSP
CSP(Content-Security-Policy): 内容安全策略
作用:
1、限制资源获取 2、报告资源获取越权
限制方式:
1、default-src限制全局 跟链接请求有关的东西,限制他的作用范围 2、制定资源类型
资源类型:
content-src img-src style-src script-src frame-src font-src media-src manifest-src
比如限制掉外来的js,比如xss攻击
<!--test.html--> <body> <script> console.log('inline js') </script> </body>
// server.js const http = require('http'); http.createServer(function(req,res){ console.log('req come', req.url); const html = fs.readFileSync('test.html'); res.writeHead(200,{ 'Content-Type': 'text/html', 'Content-Security-Policy': 'default-src http: https:' }) res.end(html); }).listen(8888); console.log('server listening on 8888'); console.log('http://localhost:8888/');
启动server,运行8888端口,发现控制台报错了,这就是Content-Security-Policy限制的作用,那么如果我通过外链的方式建立js呢
<!--test.html--> <body> <script> console.log('inline js') </script> <script src="/test.js"></script> </body>
// server.js const http = require('http'); const fs = require('fs'); http.createServer(function(req,res){ console.log('req come', req.url); if (req.url === '/') { const html = fs.readFileSync('test.html'); res.writeHead(200,{ 'Content-Type': 'text/html', 'Content-Security-Policy': 'default-src http: https:' }) res.end(html); } else { res.writeHead(200,{ 'Content-Type': 'application/javascript' }) res.end('console.log("loaded script")'); } }).listen(8888); console.log('server listening on 8888'); console.log('http://localhost:8888/');

可以发现后面的js打印出来的,内联的js被限制到了
限制只能本网站域名下到js,或者某个网站的js
'Content-Security-Policy': 'default-src \'self\' http://baidu.js'
限制表单的提交到他网
'Content-Security-Policy': 'form-action \'self\''
不想限制所有的链接,只限制script
'Content-Security-Policy': 'script-src http: https:'
更多:https://developer.mozilla.org/zh-CN/search?q=csp
也可以通过meta标签进行限制,实际效果跟返回头里面是一样的
<meta http-equiv='Content-Security-Policy' content='script-src "self"; form-action "self"'>