【中间件】安全加固
-
安装
npm i -S koa-helmet -
作用
- 将9个安全中间件集中到一起,帮助抵御常见的web安全隐患
- 实质是对 http header 的操作
-
使用写法
import helmet from "koa-helmet";app.use(helmet())- 直接设置这个,则默认开启11个安全中间件,可以观察到网页请求的header中被添加了这些东西
Content-Security-Policy: default-src 'self';base-uri 'self';block-all-mixed-content;font-src 'self' https: data:;frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests Expect-CT: max-age=0 Referrer-Policy: no-referrer Strict-Transport-Security: max-age=15552000; includeSubDomains X-Content-Type-Options: nosniff X-DNS-Prefetch-Control: off X-Download-Options: noopen X-Frame-Options: SAMEORIGIN X-Permitted-Cross-Domain-Policies: none X-XSS-Protection: 0- 对应下面的单独的11个中间件方法
app.use(helmet.contentSecurityPolicy()); app.use(helmet.dnsPrefetchControl()); app.use(helmet.expectCt()); app.use(helmet.frameguard()); app.use(helmet.hidePoweredBy()); app.use(helmet.hsts()); app.use(helmet.ieNoOpen()); app.use(helmet.noSniff()); app.use(helmet.permittedCrossDomainPolicies()); app.use(helmet.referrerPolicy()); app.use(helmet.xssFilter());
- 直接设置这个,则默认开启11个安全中间件,可以观察到网页请求的header中被添加了这些东西
-
注意!!!
- 这个中间件,最好放在 最前面 插入
-
可以单独开启某个中间件,并详细设置其中的参数
CSP- 全称 网页安全政策(Content Security Policy)
- 实质是白名单
- 明确告诉客户端,哪些域名的资源可以加载执行
- 要么通过 http header 的
Content-Security-Policy字段设置 - 要么通过 meta标签 设置
app.use( helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"], styleSrc: ["'self'", "other.trust.com"], script-src: ["'self'", "other.trust.com"], } }) );- 指定只有自己的才能加载,同时信任网站的样式style或js文件也可以加载