XSS:Cross Site Scripting
将参数中的特殊字符进行转换
<script>alert(1);</script>
<script>alert(1);</script>
使用 commons-text
包中的 StringEscapeUtils.escapeHtml4();
方法
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency>
对 HttpServletRequest
对象的请求参数进行处理
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } @Override public String getQueryString() { String value = super.getQueryString(); return StringEscapeUtils.escapeHtml4(value); } @Override public String getParameter(String name) { String value = super.getParameter(name); return StringEscapeUtils.escapeHtml4(value); } @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if (ArrayUtils.isEmpty(values)) { return values; } int length = values.length; String[] escapeValues = new String[length]; for (int i = 0; i < length; i++) { String value = values[i]; escapeValues[i] = StringEscapeUtils.escapeHtml4(value); } return escapeValues; } }
使用 WebFilter
注解,拦截所有请求,过滤请求参数
@Slf4j @WebFilter(filterName = "xssFilter", urlPatterns = "/*", asyncSupported = true) public class XssFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; XssHttpServletRequestWrapper xssHttpServletRequestWrapper = new XssHttpServletRequestWrapper(request); filterChain.doFilter(xssHttpServletRequestWrapper, servletResponse); } }
扫描使用servlet注解的类,启用 XssFilter
@ServletComponentScan
实现Jackson反序列化方法,将参数值转义处理
public class XssJacksonDeserializer extends JsonDeserializer<String> { @Override public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { return StringEscapeUtils.escapeHtml4(jsonParser.getText()); } }
实现Jackson序列化方法,将参数值转义处理
@Slf4j public class XssJacksonSerializer extends JsonSerializer<String> { @Override public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(StringEscapeUtils.escapeHtml4(s)); } }
@Configuration public class JacksonConfig implements WebMvcConfigurer { @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // code... // XSS序列化 simpleModule.addSerializer(String.class, new XssJacksonSerializer()); simpleModule.addDeserializer(String.class, new XssJacksonDeserializer()); // code... } }
实现字符串转义的核心方法:
org.apache.commons.text.StringEscapeUtils
StringEscapeUtils.escapeHtml4();