前端如何解决xss攻击

779 阅读1分钟

什么是xss攻击?

XSS 即(Cross Site Scripting)中文名称为:跨站脚本攻击。 XSS的重点不在于跨站点,而在于脚本的执行。那么XSS的原理是:恶意攻击者在web页面中会插入一些恶意的script代码。当用户浏览该页面的时候,那么嵌入到web页面中script代码会执行,因此会达到恶意攻击用户的目的。

解决办法?

前端引入xss,根据白名单过滤html,防止xss攻击;每次保存/渲染html都先调用myxss.process方法过滤。

1.安装:npm install xss

2.filterXss.js文件添加白名单

image.png

import xss from "xss";

const myxss = new xss.FilterXSS({
  whiteList: {
    u: ["contenteditable", "relateobj", "class", "style", "uid"],
    span: ["style", "class"],
    br: [],
    strong: [],
    em: [],
    p: ["style", "class"],
    div: ["class", "style"],
    h1: [],
    h2: ["class", "style"],
    h3: ["class", "style"],
    h4: ["class", "style"],
    h5: [],
    h6: [],
    table: ["style", "class", "border", "cellspacing", "cellpadding"],
    tr: [],
    td: ["class", "style"],
    colgroup: [],
    col: ["width"],
    label: ["class", "style"],
    th: [],
    style: [],
    input: ["id", "name", "type", "value", "checked", "style"],
    b: [],
    "o:p": []
  },
  css: {
    whiteList: {
      display: true,
      margin: true,
      color: true,
      "text-decoration": true,
      "font-size": true,
      "line-height": true,
      outline: true,
      "word-wrap": true,
      "text-align": true,
      "overflow-wrap": true,
      "font-family": true,
      "text-indent": true,
      clear: true,
      width: true,
      float: true,
      "table-layout": true,
      "padding-left": true,
      "margin-left": true
    }
  }
});

export default myxss;

3.引入并使用

image.png