XSS攻击的常见修复方案如下:
1. 对用户输入的数据进行 HTML 转义处理,避免恶意内容被浏览器解析为可执行脚本,从而有效防止 XSS 跨站脚本攻击,示例如下:
String result = HtmlUtils.htmlEscape(source);2. 根据白名单允许的标签与属性对内容进行过滤,并移除可执行脚本代码,这是一种常用的 XSS 过滤与安全防护方式,示例如下:
org.jsoup jsoup 1.13.1 String result = Jsoup.clean(source, Whitelist.basic());//默认的基础白名单配置public static Whitelistbasic(){return new Whitelist().addTags("a","b","blockquote","br","cite","code","dd","dL","dt","em","i","Li","oL","p","pre","q","small","span","strike","strong","sub""sup","U","uL").addAttributes(tag:"a", ...attributes:"href").addAttributes(tag:”bLockquote", ...attributes:"cite").addAttributes(tag:"q", ...attritoutes:"cite").addProtocols(tag:"a", attribute:"href", ...potocols:"ftp", "http", "https", "mailto").addProtocols(tag:"bLockquote", attribute:"cite", ...protocolo:"http", "https").addProtocols(tag:"cite",attribute:"cite", ...protocols:"http", "https").addEnforcedAttribute(tag:"a",attribute:"rel",value:"nofollow");}