网络安全漏洞防护知识一:input输入防止xss攻击的防御措施
input输入预防xss网络攻击的防御措施
1.首先项目安装 dompurify, 终端安装命令:npm i dompurify
2.在utils文件夹下面创建directives文件夹,然后在该文件夹下面创建inputFilter.js 具体内容如下:
import DOMPurify from 'dompurify';
/**
* 实现功能
* 1、默认情况下只禁止空格输入
* 2、intFilter 限制只能输入整数
* 3、priceFilter 限制只能输入整数和小数(价格类)
* 4、phoneFilter 限制只能输入手机号
* 5、specialFilter 限制最大值和最小值(抛出错误给回调函数)
* 6、domPurify 限制非法字符的输入
*/
const addListener = function(el, type, fn) {
el.addEventListener(type, fn, false)
}
const domPurify = function(el){
addListener(el, 'keyup', () => {
el.value = DOMPurify.sanitize(el.value);
el.dispatchEvent(new Event("input"));
})
}
const spaceFilter = function(el) {
addListener(el, 'keyup', () => {
el.value = el.value.replace(/\s+/, '');
el.dispatchEvent(new Event("input"));
})
}
const intFilter = function(el) {
addListener(el, 'keyup', () => {
el.value = el.value.replace(/\D/g, '');
el.dispatchEvent(new Event("input"));
})
}
const priceFilter = function(el) {
addListener(el, 'keyup', () => {
el.value = el.value.replace(/[^\d.]*/g, '')
if (isNaN(el.value)) {
el.value = ''
}
el.dispatchEvent(new Event("input"));
})
}
const specialFilter = function(el) {
addListener(el, 'keyup', () => {
el.value = el.value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '');
el.dispatchEvent(new Event("input"));
})
}
const phoneFilter = function(el) {
addListener(el, 'blur', () => {
if (!el.value) {
return
}
const phoneReg = new RegExp('^(13|14|15|16|17|18|19)[0-9]{9}$')
if (!phoneReg.test(el.value)) {
alert('手机号输入错误')
el.value = ''
}
})
}
const urlFilter = function(el) {
addListener(el, 'blur', () => {
if (!el.value) {
return
}
const urlReg = /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
if (!urlReg.test(el.value)) {
alert('url输入错误')
el.value = ''
}
})
}
export default {
bind(el, binding) {
if (el.tagName.toLowerCase() !== 'input') {
el = el.getElementsByTagName('input')[0]
}
spaceFilter(el)
switch (binding.arg) {
case 'int':
intFilter(el)
break
case 'price':
priceFilter(el)
break
case 'special':
specialFilter(el)
break
case 'phone':
phoneFilter(el)
break
case 'url':
urlFilter(el)
break
case 'dom':
domPurify(el)
break
default:
break
}
}
}
然后创建index.js文件 具体代码如下:
import inputFilter from './inputFilter'
const install = function(Vue) {
Vue.directive('inputFilter', inputFilter)
}
if (window.Vue) {
window.inputFilter = inputFilter
Vue.use(install)
}
inputFilter.install = install
export default inputFilter
最后在main.js中引入js
import DomPurify from './utils/directives/index.js'
Vue.use(DomPurify);
在vue项目中使用如下v-input-filter:dom
<el-input
type="password"
v-model="bsform.password"
placeholder="请输入密码"
autocomplete="off"
v-input-filter:dom
:show-password="true"
class="login-input"
></el-input>