当前位置:   article > 正文

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

vue-dompurify-html

背景

之前的防御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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

坑&解决方案

信心满满给业务爸爸测试,好,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']
  }
});
  • 1
  • 2
  • 3
  • 4
  • 5

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

增加hooks

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

vue.use(VueDOMPurifyHTML, {
  hooks: {
    afterSanitizeAttributes: (currentNode) => {
      if('target' in currentNode){
	  currentNode.setAttribute("target","_blank");
	  }
    }   
  }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

还有更多hook可以添加

beforeSanitizeElements
uponSanitizeElement (No 's' - called for every element)
afterSanitizeElements
beforeSanitizeAttributes
uponSanitizeAttribute
afterSanitizeAttributes
beforeSanitizeShadowDOM
uponSanitizeShadowNode
afterSanitizeShadowDOM
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

后续

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/448218
推荐阅读
相关标签
  

闽ICP备14008679号