Vue3+Ts 解决富文本编辑器潜在的XSS攻击

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);

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值