使用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防御的效果
坑&解决方案
信心满满给业务爸爸测试,好,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://net2asp.com/169ed90b1b.html
