0


使用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
标签: 前端

本文转载自: https://blog.csdn.net/qq_28722667/article/details/130074434
版权归原作者 无极之岚 所有, 如有侵权,请联系我们删除。

“使用vue-dompurify-html防御xss攻击”的评论:

还没有评论