什么是XSS攻击,攻击者往 web 页面里插入恶意的 HTML 代码(Javascript、css、html 标签等),当用户浏览该页面时,嵌入其中的 HTML 代码会被执行,从而达到恶意攻击用户的目的。如盗取用户 cookie 执行一系列操作,破坏页面结构、重定向到其他网站等。
例:(<img src=x οnerrοr=alert(localStorage.token)> 通过执行js获取一些敏感数据)
---以下是我自己进行的处理---
1.首先处理接口返回的数据,对接口返回的数据进行重新编译
res = decodeObj(res)
// 对接口进行数据的转移,防止串改接口返回的数据进行XSS攻击
//可以写一个全局ajaxReset的数据处理
// 采用递归,获取深层次数据, 每一层字符串都进行HTMLDecode的处理
function decodeObj(obj: any): any {
if (typeof obj == 'string') {
return HTMLDecode(obj) // 调取数据的转移
} else if (typeof obj == 'object' && !(obj instanceof Array) && obj !== null) {
//object
const temp: any = {}
for (const [key, value] of Object.entries(obj)) {
temp[key] = decodeObj(value)
}
return temp
} else if (typeof obj == 'object' && obj instanceof Array) {
// array
return obj.map(item => {
return decodeObj(item)
})
}
return obj
}
核心方法
// 核心方法 对数据进行转义, innerText与innerText不会被解析为HTML
//以此来防止接口返回的XSS攻击
function HTMLDecode(text: string) {
if (text && !text.includes('<')) {
text = HTMLEncode(text)
}
let temp: any = document.createElement("div")
temp.innerHTML = text
const output = temp.innerText || temp.textContent
temp = null
return output
}
// 如果<字符 将被处理成 '<'
function HTMLEncode(html: string) {
// 1.首先动态创建一个容器标签元素,如DIV
let temp: any = document.createElement("div")
// 2.然后将要转换的字符串设置为这个元素的innerText(ie支持)
// 或者textContent(火狐,google支持)
if (temp.textContent) {
temp.textContent = html
} else {
temp.innerText = html
}
// 3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了
const output = temp.innerHTML
temp = null;
return output;
}
以上就是对数据的处理。
2.处理from表单自动提交的问题,防止触发JS代码引发XSS攻击
可以看到W3C中有明确规定,当使用form组件的时候在输入框回车提交会自动提交一次表单。这样会导致你输入在input框中的数据进行执行,如果是一串js的攻击代码则会被攻击。
而使用element组件与vant组件可能会有一些不同。
// PC端 el-form中加入@submit.native.prevent 防止自动提交表单
<el-form ref="form" @submit.native.prevent></el-form>
// H5 在表单中的button 标签 type 属性的默认值为submit
//导致触发表单提交, 要注意将native-type设置为button,否则会触发表单提交。
<van-form @submit="onSubmit">
<van-field
v-model="password"
type="password"
name="密码"
label="密码"
placeholder="密码"
:rules="[{ required: true, message: '请填写密码' }]"
/>
<van-button native-type="button">提交</van-button>
</van-form>
以上就是一些处理xss攻击的方法。