XSS攻击是一种利用Web应用程序中存在的漏洞,向用户的浏览器注入恶意脚本的攻击方式。
当我们使用v-html去解析 富文本 时,遇到script标签会自动解析并运行。若不将数据进行清洗直接输出到页面上,就容易产生XSS漏洞。
例如:我们在富文本中插入一段字符串 "hello vue<img src="../qwe" οnerrοr="alert(1)">"
此时 img标签解析不了src中的路径 就会报错并弹窗。同理 ,若插入其他脚本,则可以悄无声息地获取页面中的各种信息。
一、解决方案1:使用 vue-dompurify-html 插件
(1)安装插件
yarn add vue-dompurify-html
(2) main.ts 中使用
import VueDOMPurifyHTML from 'vue-dompurify-html'
import { createApp } from 'vue'
const app = createApp(App)
app.use(VueDOMPurifyHTML)
(3) 在dom中使用
<div v-dompurify-html="richTextValue" />
支持自定义配置:具体实现见官方文档vue-dompurify-html - npm (npmjs.com)
二、解决方案2:使用html自带的清洗器:sanitize-html
//默认配置
const customConfig = {
allowedTags: ['b', 'i', 'u', 'p', 'span', 'img'],
allowedAttributes: {
img: ['src']
},
allowedSchemes: ['http', 'https'],
allowedClasses: {
b: ['bold', 'highlight'],
i: ['italic']
},
transformTags: {
b: 'strong',
i: 'em'
},
nonTextTags: ['style', 'script', 'textarea', 'noscript']
}
//使用sanitizeHtml函数返回干净的dom
const cleanHtml = sanitizeHtml(richTextValue.value, customConfig);