1 . pom中增加依赖

<!-- xss过滤组件 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>

2 . 增加标签处理类

package com.xbz.utils;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist; import java.io.IOException; /**
* xss非法标签过滤工具类
* 过滤html中的xss字符
* @author xbz
*/
public class JsoupUtil { /**
* 使用自带的basicWithImages 白名单
* 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,
* strike,strong,sub,sup,u,ul,img
* 以及a标签的href,img标签的src,align,alt,height,width,title属性
*/
private static final Whitelist whitelist = Whitelist.basicWithImages();
/** 配置过滤化参数,不对代码进行格式化 */
private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
static {
// 富文本编辑时一些样式是使用style来进行实现的
// 比如红色字体 style="color:red;"
// 所以需要给所有标签添加style属性
whitelist.addAttributes(":all", "style");
} public static String clean(String content) {
if(StringUtils.isNotBlank(content)){
content = content.trim();
}
return Jsoup.clean(content, "", whitelist, outputSettings);
} public static void main(String[] args) throws IOException {
String text = " <a href=\"http://www.baidu.com/a\" onclick=\"alert(1);\">sss</a><script>alert(0);</script>sss ";
System.out.println(clean(text));
}
}

3 . 重写请求参数处理函数

package com.xbz.web.common.filter;

import com.xbz.utils.JsoupUtil;
import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; /**
* <code>{@link XssHttpServletRequestWrapper}</code>
* @author
*/
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
private boolean isIncludeRichText = false; public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) {
super(request);
orgRequest = request;
this.isIncludeRichText = isIncludeRichText;
} /**
* 覆盖getParameter方法,将参数名和参数值都做xss过滤。<br/>
* 如果需要获得原始的值,则通过super.getParameterValues(name)来获取<br/>
* getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
*/
@Override
public String getParameter(String name) {
Boolean flag = ("content".equals(name) || name.endsWith("WithHtml"));
if( flag && !isIncludeRichText){
return super.getParameter(name);
}
name = JsoupUtil.clean(name);
String value = super.getParameter(name);
if (StringUtils.isNotBlank(value)) {
value = JsoupUtil.clean(value);
}
return value;
} @Override
public String[] getParameterValues(String name) {
String[] arr = super.getParameterValues(name);
if(arr != null){
for (int i=0;i<arr.length;i++) {
arr[i] = JsoupUtil.clean(arr[i]);
}
}
return arr;
} /**
* 覆盖getHeader方法,将参数名和参数值都做xss过滤。<br/>
* 如果需要获得原始的值,则通过super.getHeaders(name)来获取<br/>
* getHeaderNames 也可能需要覆盖
*/
@Override
public String getHeader(String name) {
name = JsoupUtil.clean(name);
String value = super.getHeader(name);
if (StringUtils.isNotBlank(value)) {
value = JsoupUtil.clean(value);
}
return value;
} /**
* 获取最原始的request
*
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
} /**
* 获取最原始的request的静态方法
*
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
if (req instanceof XssHttpServletRequestWrapper) {
return ((XssHttpServletRequestWrapper) req).getOrgRequest();
} return req;
} }

4 . 编写XSSFilter

package com.xbz.web.common.filter;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* 拦截防止xss注入
* 通过Jsoup过滤请求参数内的特定字符
* @author yangwk
*/
public class XssFilter implements Filter {
private static final Logger logger = LogManager.getLogger(); /**
* 是否过滤富文本内容
*/
private static boolean IS_INCLUDE_RICH_TEXT = false; public List<String> excludes = new ArrayList<>(); @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException {
if(logger.isDebugEnabled()){
logger.debug("xss filter is open");
} HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if(handleExcludeURL(req, resp)){
filterChain.doFilter(request, response);
return;
} XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT);
filterChain.doFilter(xssRequest, response);
} private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { if (excludes == null || excludes.isEmpty()) {
return false;
} String url = request.getServletPath();
for (String pattern : excludes) {
Pattern p = Pattern.compile("^" + pattern);
Matcher m = p.matcher(url);
if (m.find()) {
return true;
}
} return false;
} @Override
public void init(FilterConfig filterConfig) throws ServletException {
if(logger.isDebugEnabled()){
logger.debug("xss filter init ====================");
}
String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
if(StringUtils.isNotBlank(isIncludeRichText)){
IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
} String temp = filterConfig.getInitParameter("excludes");
if (temp != null) {
String[] url = temp.split(",");
for (int i = 0; url != null && i < url.length; i++) {
excludes.add(url[i]);
}
}
} @Override
public void destroy() {} }

5 .  增加XSS配置

package com.xbz.web.common.config;

import com.xbz.web.common.filter.XssFilter;
import com.google.common.collect.Maps;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.Map; @Configuration
public class XssConfig{ /**
* xss过滤拦截器
*/
@Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new XssFilter());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
Map<String, String> initParameters = Maps.newHashMap();
initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
initParameters.put("isIncludeRichText", "true");
filterRegistrationBean.setInitParameters(initParameters);
return filterRegistrationBean;
}
}

大功告成, 另外SpringMVC版本的XSS防范请参考另一篇文章SpringMVC防止XSS攻击

转自https://blog.csdn.net/xingbaozhen1210/article/details/78860079

SpringBoot防XSS攻击的更多相关文章

  1. 【前端安全】JavaScript防XSS攻击

    什么是XSS XSS(Cross Site Scripting),跨站脚本攻击,是一种允许攻击者在另外一个用户的浏览器中执行恶意代码脚本的脚本注入式攻击.本来缩小应该是CSS,但为了和层叠样式(Cas ...

  2. HTML标签防XSS攻击过滤模块--待优化

    HTML标签防XSS攻击过滤模块 http://cnodejs.org/topic/5058962f8ea56b5e7806b2a3

  3. java请求URL带参之防XSS攻击

    1.web.xml新增filter配置 <!-- URL请求参数字符过滤或合法性校验 --> <filter> <filter-name>XssFilter< ...

  4. 防xss攻击

    官方:https://jsxss.com/zh/index.html xss csrf https://www.cnblogs.com/443855539-wind/p/6055816.html 一. ...

  5. webform非表单提交时防xss攻击

     1.webform默认配置下,主动防御了针对表单提交的xss攻击,但这次发生时因为url导致的,所以webform的默认防御机制不起作用  webform下输出非表单提交获得的数据的时候,要加htm ...

  6. PHP 防xss攻击

    PHP直接输出html的,可以采用以下的方法进行过滤: 1.htmlspecialchars函数 2.htmlentities函数 3.HTMLPurifier.auto.php插件 4.Remove ...

  7. [BUGCASE]CI框架的post方法对url做了防xss攻击的处理引发的文件编码错误

    一.问题描述 出现问题的链接: http://adm.apply.wechat.com/admin/index.php/order/detail?country=others&st=1& ...

  8. node防xss攻击插件

    var xss = require('node-xss').clean; router.post("/orders/insert-orders", function (req, r ...

  9. 防XSS攻击解决方法

    1.web.xml文件中新增filter配置 <!-- URL请求参数字符过滤或合法性校验 --> <filter> <filter-name>XssFilter& ...

随机推荐

  1. docker-compose (单机版的容器编排工具)

    类似于ansible剧本 yml 格式 要使用这个编排工具,必须先安装 yum install -y docker-compose cd wordpress/ vi docker-compose.ym ...

  2. Jodd - Java界的瑞士军刀轻量级工具包!

    Jodd介绍 Jodd是对于Java开发更便捷的开源迷你框架,包含工具类.实用功能的集合,总包体积不到1.7M. Jodd构建于通用场景使开发变得简单,但Jodd并不简单!它能让你把事情做得更好,实现 ...

  3. 7_2.springboot2.x启动配置原理_2.运行run方法

    当创建完SpringApplication对象之后运行run方法 public ConfigurableApplicationContext run(String... args) { StopWat ...

  4. Python操作三大主流数据库✍✍✍

    Python操作三大主流数据库 Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口. Python 数据库接口支持非常多的数据库, ...

  5. <jquery>基本的模态框

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. 2019-11-7-C#-dotnet-线程不安全的弱引用缓存

    title author date CreateTime categories C# dotnet 线程不安全的弱引用缓存 lindexi 2019-11-7 9:45:5 +0800 2019-11 ...

  7. Luogu P4246 [SHOI2008]堵塞的交通(线段树+模拟)

    P4246 [SHOI2008]堵塞的交通 题意 题目描述 有一天,由于某种穿越现象作用,你来到了传说中的小人国.小人国的布局非常奇特,整个国家的交通系统可以被看成是一个\(2\)行\(C\)列的矩形 ...

  8. golang 获取当前可执行程序的当前路径

    import ( "errors" // "fmt" "os" "os/exec" "path/filepat ...

  9. 【JZOJ3316】非回文数字

    description 如果一个字符串从后往前读与从前往后读一致,我们则称之为回文字符串.当一个数字不包含长度大于1的子回文数字时称为非回文数字.例如,16276是非回文数字,但17276不是,因为它 ...

  10. Failed to load resource: net::ERR_INSECURE_RESPONSE 问题解决记录

    项目在小米自带浏览器中出现了文件丢失.经检查发现这些链接引用全部是完整的线上url.改为相对路径问题解决. 同时消失的bug还有一个Error in event handler for runtime ...