[头参数]10 - CSP

目录

  1. 不允许在script中直接写js代码
  2. 更多的加载url相关的参数
  3. 表单相关
  4. 出错报告

0. 概述

  1. CSP是一个网站安全相关的参数,主要对加载url与访问url进行控制。
  2. 使用的响应头参数是Content-Security-Policy

1. 不允许在script中直接写js代码

  • 在html分别创建两种script


  • 设置响应头参数

设置的值的意思是仅允许使用src加载js代码,仅允许使用http(需要注意的是参数值为http:

/**
 * 1. 不允许在script标签中写代码
 */
const http = require('http')
const fs =require('fs')
const port = 9000

http.createServer(function (request, response) {

    const url = request.url
    const html = fs.readFileSync('index.html', 'utf-8')

    switch(url) {
      case '/': {
        response.writeHead(200, {
          'Content-Type': 'text/html',
          // 不允许在script中写代码
          'Content-Security-Policy': 'default-src http:'
        })
        response.end(html)
      }
      case '/test.js': {
        response.writeHead(200, {
          'Content-Type': 'text/javascript',
        })
        response.end('console.log("It is test.js")')
      }
    }

}).listen(port)

console.log("serve is listen ", port)
  • 测试

可以看到只显示了使用src加载的输出,写代码的方式报错。


[头参数]10 - CSP_第1张图片

2. 更多的加载url相关的参数

  • 'Content-Security-Policy': 'http://xxxxxx' 只允许加载指定网站的资源
  • 'Content-Security-Policy': '\'self\'' 只允许加载自己网站的资源
  • CSP-参考网站

3. 表单相关

  • 设计一个表单,提交到百度首页
  • 限制表单的提交的url
  1. 使用前缀form-action
  2. 如果同时需要上面的内容,则使用;隔开
  3. \self\限制了只能往自身的网站提交
/**
 * 1. CSP中表单相关
 */
const http = require('http')
const fs =require('fs')
const port = 9000

http.createServer(function (request, response) {

    const url = request.url
    const html = fs.readFileSync('form.html', 'utf-8')

    switch(url) {
      case '/': {
        response.writeHead(200, {
          'Content-Type': 'text/html',
          // 不允许往外站提交表单
          'Content-Security-Policy': 'form-action \'self\''
        })
        response.end(html)
      }
    }  

}).listen(port)

console.log("serve is listen ", port)
  • 测试

点击按钮,查看终端内容


  • 更改参数值
'Content-Security-Policy': 'form-action https://www.baidu.com/'

更改后在测试,则成功跳转到百度首页。

4. 出错报告

  • 增加report-uri参数,设置出错后访问的uri
'Content-Security-Policy': 'form-action \'self\'; report-uri /report'
  • 测试

可以看到浏览器向我们指定的uri传递了一个csp-report对象,服务端可从对象中提取数据,进行一定的处理

[头参数]10 - CSP_第2张图片

你可能感兴趣的:([头参数]10 - CSP)