介绍
内容安全策略 (CSP) 是一个附加的安全层,用于帮助检测和缓解某些类型的攻击,包括跨站脚本 (XSS) 和数据注入等攻击。 这些攻击可用于实现从数据窃取到网站破坏或作为恶意软件分发版本等用途。
启动方式
1. 浏览器客户端启动
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
2. 服务器nginx启动
server {
listen 3012 ;
server_name localhost;
#即所有请求都到这里去找分配
location / {
root html/dist;
try_files $uri $uri/ /index.html;
add_header Content-Security-Policy "default-src 'self' 'unsafe-inline' data:;";
add_header X-Xss-Protection "1;mode=block";
add_header X-Content-Type-Options nosniff;
index index.html;
}
例子
// 限制所有的外部资源,都只能从当前域名加载
Content-Security-Policy: default-src 'self'
// default-src 是 CSP 指令,多个指令之间用英文分号分割;多个指令值用英文空格分割
Content-Security-Policy: default-src https://host1.com https://host2.com; frame-src 'none'; object-src 'none'
// 错误写法,第二个指令将会被忽略
Content-Security-Policy: script-src https://host1.com; script-src https://host2.com
// 正确写法如下
Content-Security-Policy: script-src https://host1.com https://host2.com
// 通过report-uri指令指示浏览器发送JSON格式的拦截报告到某个地址
Content-Security-Policy: default-src 'self'; ...; report-uri /my_amazing_csp_report_parser;