使用vue-dompurify-html防御xss攻击

背景

之前的防御xss攻击的前端方案太low,影响到了现网用户的体验,但是富文本渲染势不可挡,v-html确实又会被xss攻击,这时vue-dompurify-html就来了!!

使用

我们这里还是以vue2为例

npm install vue-dompurify-html
// 在main.js中引入
import Vue from 'vue'
import VueDOMPurifyHTML from 'vue-dompurify-html'

Vue.use(VueDOMPurifyHTML)

// 在vue页面中使用,就可以达到xss防御的效果
 <div v-dompurify-html="rawHtml"></div>

坑&解决方案

信心满满给业务爸爸测试,好,a标签的target="_blank"属性给干没了,这可是很重要的属性,上官网看看

https://www.npmjs.com/package/vue-dompurify-html/v/2.6.0


you can also config,那就来config一下。

重写属性配置

https://github.com/cure53/DOMPurify#can-i-configure-dompurify

Vue.use(VueDOMPurifyHTML, {
  default: {
    ALLOWED_ATTR: ['target','href']
  }
});

但是a标签的其他属性全被过滤了,原来这就是覆盖默认配置!那可不行

增加hooks

在处理属性后,如果有target属性的节点,统统加上target=blank

vue.use(VueDOMPurifyHTML, {
  hooks: {
    afterSanitizeAttributes: (currentNode) => {
      if('target' in currentNode){
	  currentNode.setAttribute("target","_blank");
	  }
    }   
  }
});

还有更多hook可以添加

beforeSanitizeElements
uponSanitizeElement (No 's' - called for every element)
afterSanitizeElements
beforeSanitizeAttributes
uponSanitizeAttribute
afterSanitizeAttributes
beforeSanitizeShadowDOM
uponSanitizeShadowNode
afterSanitizeShadowDOM

后续

看文档,还有更多的方法可以使用,主要结合npm install dompurify

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值