vue 解决v-html指令存在xss漏洞

1,120 阅读1分钟

前言:前端xss攻击很多人都遇到过,原理和攻击方式是什么这里就不赘述,很多文章那里都能看的到,这里讲一下怎么防范

1.引入资源

// 引入资源
yarn add xss 
npm install xss

2.使用方法

  1. 新增xss.js
import Vue from 'vue'
import xss from 'xss'
// 使用默认配置加自定义配置
const css = xss.getDefaultCSSWhiteList()
const tag = xss.getDefaultWhiteList()
// 例如
// css.background = false // css style中禁止使用background 属性
// tag.a = ['style'] // 只允许a标签中存在 style属性
const options = {
  stripIgnoreTagBody: true, // 不在白名单中的标签以及标签里面的内容直接删除
  whiteList: tag,
  css: {
    whiteList: css
  }
}
const xssFn = (str) => {
  return xss(str, options)
}
// 全局注册xss指令
Vue.prototype.xss = xssFn

export {
  xssFn as xss
}

2.修改

// main.js 中引入 xss.js
import './core/directives/xss'
// vue.config.js chainWebpack 中加入
// 覆写html指令
config.module.rule('vue').use('vue-loader').loader('vue-loader').tap(options => {
  options.compilerOptions.directives = {
    html(node, directiveMeta) {
      (node.props || (node.props = [])).push({
        name: 'innerHTML',
        value: `xss(_s(${directiveMeta.value}))`
      })
    }
  }
  return options
})

此时使用v-html会默认过滤xss, 如果有标签和属性被过滤掉,需在xss.js中新增自定义属性,

更多问题 jsxss.com/zh/index.ht…